【问题标题】:Problem with scatter plot legend using matplotlib使用 matplotlib 散点图图例的问题
【发布时间】:2022-07-14 21:42:11
【问题描述】:

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

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

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

以前有人遇到过这个问题吗?

参考代码sn-p:

    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))
     

生成的图表: Hotend Temperature vs. Max Force Scatter Graph

【问题讨论】:

    标签: python matplotlib data-visualization legend scatter-plot


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      输出图

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

      【讨论】:

        最近更新 更多