【问题标题】:Creating label in Scatter Matplotlib from dataFrame从 dataFrame 在 Scatter Matplotlib 中创建标签
【发布时间】:2020-04-26 12:28:28
【问题描述】:

我有如下示例所示的 DataFrame (dfcell):

这个 DataFrame 有 104 行,我需要在散点图中显示。

location_cell_lnglocation_cell_lat 列是笛卡尔坐标轴,class_m 是目标。

我做到了

plt.scatter(dfcell['location_cell_lng'], dfcell['location_cell_lat'], c=dfcell['class_m'])

我无法将图例放在范围为 0 到 5 的 class_m 列中。

我尝试了下面链接中的代码,但没有成功 https://matplotlib.org/gallery/lines_bars_and_markers/scatter_with_legend.html#sphx-glr-gallery-lines-bars-and-markers-scatter-with-legend-py

我该怎么做?

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    label="mylabel" 作为参数添加到plt.scatter 然后调用plt.legend()方法

    # dummy data for classes
    class_m = [ 0 for x in range(5)] + [ 1 for x in range(5)]
    
    # create dataframe
    dfcell = pd.DataFrame({"location_cell_lng":range(10),"location_cell_lat":range(10),"class_m":class_m})
    
    # create a dictionary to color the different classes
    color_dict = {0:"red",1:"blue"}
    
    # create column with colors
    dfcell["colors"] = dfcell["class_m"].apply(color_dict.get)
    
    # plot
    plt.scatter(dfcell['location_cell_lng'], dfcell['location_cell_lat'], c=dfcell['colors'],label="mylabel")
    plt.legend()
    

    【讨论】:

    • 您好帕特里克,感谢您的回答!但我需要根据价值目标(class_m)不同的颜色
    • 我已经编辑了答案,以展示如何根据不同的类别进行着色。
    猜你喜欢
    • 1970-01-01
    • 2017-05-27
    • 2012-11-04
    • 2015-12-09
    • 1970-01-01
    • 2020-03-27
    • 2017-04-10
    • 2023-03-17
    • 2021-08-17
    相关资源
    最近更新 更多