繁体   English   中英

使用 matplotlib 散点图图例的问题

[英]Problem with scatter plot legend using matplotlib

使用 matpotlib 创建散点图时,我的图例格式出现问题。 在这种情况下,数据本身被正确绘制在散点图上,但图例的值不正确。

正如您从附图中看到的 - 热端温度数据的形式为 175ºC、185ºC、195ºC、205ºC...,但图例显示的是四舍五入的值(180、190、200、210...)。

图例也有 10 个条目,而应该有 11 个(175ºC - 275ºC,间隔为 10)。

有没有人遇到过这个问题?

代码片段供参考:

    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 tempaerature 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))
    
    handles, labels = scatter.legend_elements()
    legend = ax3.legend(handles, labels, title="{}".format(varcap),loc='center left', bbox_to_anchor=(1.02 , 0.5))
     

生成的图表:热端温度与最大力散点图

我认为您应该检查/更改的行是: handles, labels = scatter.legend_elements()

函数legend_elements()有一个名为num的参数,用于调整您希望图例拥有的条目数,您可以在此处查看文档。

如果您在代码中打印handles ,您将看到只有 10 个条目。 出于某种原因,默认设置为 10。将其更改为 9 或 11 不会更改它。 增加超过会给你像 176,184 等数字。相反,将scatter.legend_elements()替换为None 这将使它使用所有独特的元素。 所以,用这个代替你所拥有的......

handles, labels = scatter.legend_elements(prop='colors', num=None)

输出图

在此处输入图像描述

注意:我使用了 random x 并注释掉了与 varcap 相关的行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM