【问题标题】:Add legend to scatter plot to differentiate colours?在散点图中添加图例以区分颜色?
【发布时间】:2016-08-31 04:42:57
【问题描述】:

我正在使用 Pandas 0.18。我有一个这样的数据框:

code    proportion    percent_highcost    total_quantity
A81     0.7           76                  1002
A81     0.0           73                  1400

我正在绘制这样的散点图:

colours = np.where(df['proportion'] > 0, 'r', 'b')  
df.plot.scatter(y='percent_highcost', x='total_quantity', c=colours)

这很好用,但我不知道如何添加图例来指示两种颜色的含义。

我试过 plt.legend(['Non-dispensing', 'dispensing'], loc=1) 但这会产生奇怪的结果 - 我猜是因为只有一个系列:

谁能给点建议?

【问题讨论】:

  • 我建议使用fig.colorbar(sc),其中sc 是艺术家scatter。您可能必须使用 ax.scatter 而不是 df.plot 才能轻松访问该艺术家。

标签: python pandas matplotlib


【解决方案1】:

在同一轴上绘制唯一的DataFrames

在散点图中绘制多个系列(不是pandasSeries)可以通过按条件分隔DataFrames 然后将它们绘制为具有独特颜色的单独散点图来完成同一轴。这在answer 中显示。我将在这里用你的数据重现它。

注意:这是在 iPython/Jupyter notebook 中完成的

%matplotlib inline

import pandas as pd
from cStringIO import StringIO  

# example data
text = '''
code    proportion    percent_highcost    total_quantity
A81     0.7           76                  1002
A81     0.0           73                  1400
A81     0.1           77                  1300
A81     0.0           74                  1200
A81     -0.1          78                  1350
'''

# read in example data
df = pd.read_csv(StringIO(text), sep='\s+')

print 'Original DataFrame:'
print df
print

# split the DataFrame into two DataFrames
condition = df['proportion'] > 0
df1 = df[condition].dropna()
df2 = df[~condition].dropna()

print 'DataFrame 1:'
print df1
print

print 'DataFrame 2:'
print df2
print

# Plot 2 DataFrames on one axis
ax = df1.plot(kind='scatter', x='total_quantity', y='percent_highcost', c='b', s=100, label='Non-Dispensing')
df2.plot(kind='scatter', x='total_quantity', y='percent_highcost', c='r', s=100, label='Dispensing', ax=ax)

Original DataFrame:
  code  proportion  percent_highcost  total_quantity
0  A81         0.7                76            1002
1  A81         0.0                73            1400
2  A81         0.1                77            1300
3  A81         0.0                74            1200
4  A81        -0.1                78            1350

DataFrame 1:
  code  proportion  percent_highcost  total_quantity
0  A81         0.7                76            1002
2  A81         0.1                77            1300

DataFrame 2:
  code  proportion  percent_highcost  total_quantity
1  A81         0.0                73            1400
3  A81         0.0                74            1200
4  A81        -0.1                78            1350

【讨论】:

    猜你喜欢
    • 2019-11-03
    • 2020-02-15
    • 1970-01-01
    • 2017-06-30
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 2021-10-29
    相关资源
    最近更新 更多