You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用-0.1至0.1的数组定义散点图边缘色?代码问题求助

Hey there! Let's sort out that edge color problem you're facing with your scatter plot. The issue here is that when you call plt.cm.coolwarm(colors) directly, it expects input values to be normalized between 0 and 1. Since your deltf ranges from -0.1 to 0.1, all negative values get clamped to 0, and the small positive values barely move past the start of the colormap—resulting in all edges looking the same.

Here's how to fix it, with two straightforward approaches:

Approach 1: Use ScalarMappable (clean and explicit)

This method properly maps your -0.1 to 0.1 range across the full coolwarm colormap, so negatives show up as blue tones and positives as red tones:

import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable

def scatterplot(part):
    deltf = part['deltf']
    # Define the normalization range to match your data
    norm = plt.Normalize(vmin=-0.1, vmax=0.1)
    # Create a mapper to convert deltf values to colors
    color_mapper = ScalarMappable(norm=norm, cmap='coolwarm')
    edge_colors = color_mapper.to_rgba(deltf)
    
    plt.scatter(
        part['fnormal'], 
        part['mu']/part['E'], 
        c='w',  # Keep fill color white
        edgecolors=edge_colors, 
        alpha=0.5, 
        marker="o"
    )
    # Optional: Add a colorbar to show the value-color relationship
    plt.colorbar(color_mapper)

Approach 2: Normalize values first, then pass to colormap

If you prefer a more concise version, you can normalize your deltf values directly before feeding them to plt.cm.coolwarm:

import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable

def scatterplot(part):
    deltf = part['deltf']
    norm = plt.Normalize(vmin=-0.1, vmax=0.1)
    # Normalize deltf to 0-1 range, then get colors
    edge_colors = plt.cm.coolwarm(norm(deltf))
    
    plt.scatter(
        part['fnormal'], 
        part['mu']/part['E'], 
        c='w',
        edgecolors=edge_colors,
        alpha=0.5,
        marker="o"
    )
    # Add colorbar for clarity
    plt.colorbar(ScalarMappable(norm=norm, cmap='coolwarm'))

Why this works

By explicitly setting vmin=-0.1 and vmax=0.1 in Normalize, we stretch your entire data range to fit the full coolwarm colormap. This means:

  • -0.1 maps to the deep blue end of the colormap
  • 0 maps to the middle (white/light gray)
  • 0.1 maps to the deep red end

No more clamped values, and your edges will show the full range of colors you expect!

内容的提问来源于stack exchange,提问作者HanZH. LI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 08:47:30