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

使用Matplotlib绘制散点图时图例显示异常的问题求助

解决Matplotlib散点图图例数值错误与条目缺失问题

我之前也碰到过一模一样的情况!问题根源出在scatter.legend_elements()的默认行为上——它会把你的温度数值当成连续数据处理,自动划分颜色区间并生成标签,这就导致了数值被取整、条目数量和实际离散值不匹配的问题。

问题原因拆解

你的热端温度是11个固定的离散值(175℃到275℃,间隔10℃),但scatter.legend_elements()默认会根据颜色映射的分布自动生成图例条目,而非精准匹配每个离散温度值,所以才会出现标签向上取整、少一个条目的情况。

解决方案:手动创建精准匹配的图例

既然温度是固定的离散值,我们可以手动遍历每个唯一温度值,创建对应的图例手柄和标签,完全匹配你的数据。修改代码如下:

fig, ax3 = plt.subplots()
x = comb_df['level']
y = comb_df['max_force']
scatter = ax3.scatter(x,y,c=x)
ax3.set_xlabel('{}'.format(varcap) + " ({})".format(unit))
ax3.set_ylabel('Max Force (N)')
# Plot trendline
x = comb_df['level']
y = comb_df['max_force']
tline = np.polyfit(x,y, 2)
p = np.poly1d(tline)
ax3.plot(x, p(x), "r--", alpha = 0.5)
# Shrink current axis by 20%
box = ax3.get_position()
ax3.set_position([box.x0, box.y0, box.width * 0.8, box.height])
# Set custom tick labels if temperature is being plotted
if var == "hotend_temp":
    ax3.set_xticks([175,195,215,235,255,275])
    ax3.set(ylim=(50, 101))
plt.title('{} - Max Force Scatter Plot'.format(varcap))

# ------------------- 自定义图例部分 -------------------
# 获取所有唯一温度值并排序,保证顺序正确
unique_temps = sorted(comb_df['level'].unique())
handles = []
labels = []
for temp in unique_temps:
    # 为每个温度值生成匹配颜色的散点手柄
    handle = plt.Line2D([0], [0], marker='o', color='w', 
                        markerfacecolor=scatter.cmap(scatter.norm(temp)), 
                        markersize=10)
    handles.append(handle)
    labels.append(f"{temp}ºC")
# 添加自定义图例
legend = ax3.legend(handles, labels, title="{}".format(varcap), 
                    loc='center left', bbox_to_anchor=(1.02 , 0.5))
# ------------------- 自定义图例结束 -------------------

额外说明

  • 用scatter.cmap(scatter.norm(temp))可以精准获取每个温度对应的散点颜色,保证图例和图表颜色完全一致。
  • 如果你确定温度范围是固定的175-275℃,也可以直接用unique_temps = list(range(175, 285, 10))替代从数据中获取,这样更直接。

内容的提问来源于stack exchange,提问作者tom_walkr

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 22:12:37