【问题标题】:Plotting columns x and y of pandas dataframe with third column value determining the shape of the points绘制熊猫数据框的 x 和 y 列,第三列值确定点的形状
【发布时间】:2017-07-16 18:51:28
【问题描述】:

我有这个要求。我在一个文本文件中有一个示例数据,每行包含 3 个属性。 Test1 得分、Test2 得分和通过或失败表示为 1 或 0。 示例:-

 Score1 Score2 Result
 35.00 55.00 0
 45.00 34.00 0
 50.00 75.00 0
 80.00 80.00 1
 55.00 85.00 1
 67.03 66.03 0
 ..
 ..

现在我正在尝试针对 X 轴绘制 Score1 和针对 Y-axis 绘制 Score2 ,但是当我绘制点和在不同的颜色(例如绿色的“+”而红色的“o”)

我写的代码如下:-

 pos=y[y==1]
 neg=y[y==0]
 get_ipython().magic('matplotlib inline')

 ax=X.plot(kind='scatter',x='Score1',y='Score2',s=pos*10,color='DarkGreen', label='Pass');        
 X.plot(kind='scatter', x='Score1', y='Score2', s=neg*200, color='Red',   label='Fail',ax=ax);

我不确定这是否正确,因为我只能看到通过结果的图,但看不到我要求的颜色,而我的失败结果没有被绘制出来。 我在这里做错了什么?

【问题讨论】:

    标签: python-3.x pandas dataframe plot


    【解决方案1】:

    使用字典来定义每个结果类型的标记
    使用groupby 遍历类型

    m = {0: 'o', 1: '+'}
    fig, ax = plt.subplots(1, 1)
    for n, g in X.groupby('Result'):
        g.plot.scatter(
            'Score1', 'Score2', marker=m[n], ax=ax)
    

    【讨论】:

    • 感谢您的回复。如何使用您的示例代码设置正确的颜色?
    • @sunny 使用与标记相同的技巧。使用参数颜色。
    【解决方案2】:

    您可以使用boolean indexing 进行过滤:

    pos=y[y.Result==1]
    neg=y[y.Result==0]
    
    ax=pos.plot(kind='scatter',
                x='Score1',
                y='Score2',
                s=100,
                color='DarkGreen', 
                label='Pass', 
                marker='+')    
    
    neg.plot(kind='scatter', 
             x='Score1', 
             y='Score2', 
             s=50, 
             color='Red',  
             label='Fail',
             marker='o',
             ax=ax)
    
    patches, labels = ax.get_legend_handles_labels()
    ax.legend(patches, labels, loc='upper left', scatterpoints=1)
    

    【讨论】:

    • 谢谢。我应该告诉你 Y 是一个系列。但是我在 X 本身上使用了你的代码并且工作了。欣赏它。
    猜你喜欢
    • 2017-06-09
    • 2017-01-09
    • 2017-07-18
    • 2013-07-22
    • 2017-10-09
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 2022-01-20
    相关资源
    最近更新 更多