python - 使用索引进行散点图图例

标签 python pandas matplotlib scatter-plot

我创建了一个包含一些股票信息的 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()

结果:

enter image description here

关于python - 使用索引进行散点图图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38235870/

相关文章:

python - 让线程在Python中正确共享数据

python - 如何根据 ID 号列表乘以列值?

python - 在 Python 中将每月数据转换为每日数据

python - Seaborn Plot 不显示

python - 如何使用 Python 填写使用下拉日历选择日期的 Web 表单?

python - Django CMS App Hook 教程

python - 在大文件中搜索每第 n 个行模式,然后为下一个 x 行范围添加前缀

python - 给定一个代表值频率的 Pandas 系列,我如何将这些频率转换为百分比?

python - 基于两个因素可视化错误

python - 在 specgram matplotlib 中切割未使用的频率