将索引用于散点图图例
Using Index for scatter plot Legend
我创建了一个包含一些股票信息的 DataFrame。当我尝试使用索引作为数据标签时,它不起作用。这使得我无法区分股票,尤其是当我添加更多股票时。当我绘制图例时,它会显示索引列表、数据类型和名称。好像是把每一点都组合成一个标签。
我的Table:
Dividend ExpenseRatio Net_Assets PriceEarnings PriceSales
Ticker
ijr 0.0142 0.12 18.0 20.17 1.05
ijh 0.0159 0.12 27.5 20.99 1.20
我的绘图代码:
plt.scatter( df.PriceSales, df.PriceEarnings, label = df.index)
plt.xlabel('PriceSales')
plt.ylabel('PriceEarnings')
plt.legend()
plt.show()
我的图例输出:
Index(['ijr', 'ijh'],dtype='object',name='Ticker')
我可能是错的,但我认为当您的索引是您想要单独绘制的唯一文本标签时,label=df.index
将不起作用。如果您的索引是唯一的(或者如果它是一个 groupby),您可以使用 for
循环在单个图中绘制各个代码行,并为它们指定唯一的颜色 (c=np.random.rand(3,1)
)。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame({'Dividend': [0.0142, 0.0159], 'ExpenseRatio': [0.12, 0.12],
'Net_Assets': [18.0, 27.5], 'PriceEarnings': [20.17, 20.99],
'PriceSales': [1.05, 1.2]},
columns=['Dividend', 'ExpenseRatio', 'Net_Assets', 'PriceEarnings', 'PriceSales'],
index=['ijr', 'ijh'])
df.index.name = 'Ticker'
for ticker,row in df.iterrows():
plt.scatter(row['PriceSales'], row['PriceEarnings'], label=ticker, c=np.random.rand(3,1), s=100)
plt.xlabel('PriceSales')
plt.ylabel('PriceEarnings')
plt.legend()
plt.show()
结果:
我创建了一个包含一些股票信息的 DataFrame。当我尝试使用索引作为数据标签时,它不起作用。这使得我无法区分股票,尤其是当我添加更多股票时。当我绘制图例时,它会显示索引列表、数据类型和名称。好像是把每一点都组合成一个标签。
我的Table:
Dividend ExpenseRatio Net_Assets PriceEarnings PriceSales
Ticker
ijr 0.0142 0.12 18.0 20.17 1.05
ijh 0.0159 0.12 27.5 20.99 1.20
我的绘图代码:
plt.scatter( df.PriceSales, df.PriceEarnings, label = df.index)
plt.xlabel('PriceSales')
plt.ylabel('PriceEarnings')
plt.legend()
plt.show()
我的图例输出:
Index(['ijr', 'ijh'],dtype='object',name='Ticker')
我可能是错的,但我认为当您的索引是您想要单独绘制的唯一文本标签时,label=df.index
将不起作用。如果您的索引是唯一的(或者如果它是一个 groupby),您可以使用 for
循环在单个图中绘制各个代码行,并为它们指定唯一的颜色 (c=np.random.rand(3,1)
)。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame({'Dividend': [0.0142, 0.0159], 'ExpenseRatio': [0.12, 0.12],
'Net_Assets': [18.0, 27.5], 'PriceEarnings': [20.17, 20.99],
'PriceSales': [1.05, 1.2]},
columns=['Dividend', 'ExpenseRatio', 'Net_Assets', 'PriceEarnings', 'PriceSales'],
index=['ijr', 'ijh'])
df.index.name = 'Ticker'
for ticker,row in df.iterrows():
plt.scatter(row['PriceSales'], row['PriceEarnings'], label=ticker, c=np.random.rand(3,1), s=100)
plt.xlabel('PriceSales')
plt.ylabel('PriceEarnings')
plt.legend()
plt.show()
结果: