【问题标题】:Iterate Pandas Series to create a new chart legend迭代 Pandas 系列以创建新的图表图例
【发布时间】:2018-03-19 16:09:00
【问题描述】:

在分组等之后,我得到了一个如下例所示的系列。我想显示每个条的平均数字。下面的代码只显示了一个条目(当然,因为我只有一个“图例”)。谁能建议一种显示这些数字的聪明方法?

%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
import pandas

# create Series
dict_ = {"Business" : 104.04,"Economy":67.04, "Markets":58.56, "Companies":38.48}
s = pandas.Series(data=dict_)

# plot it
ax = s.plot(kind='bar', color='#43C6DB', stacked=True, figsize=(20, 10), legend=False)
plt.tick_params(axis='both', which='major', labelsize=14)
plt.xticks(rotation=30) #rotate labels
# Shrink current axis by 20%
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
#create new legend
legend = ['%s (%.1f a day)' %(i, row/7) for i, row in s.iteritems()]
# Put the legend to the right of the current axis
L = ax.legend(legend, loc='center left', bbox_to_anchor=(1, 0.5), fontsize=18)
plt.show()

【问题讨论】:

    标签: python-2.7 pandas matplotlib


    【解决方案1】:

    图例只有一个条目。这是一个蓝色条的句柄。因此,即使您将标签设置为更长的列表,也只有该列表的第一个元素用作现有句柄的标签。

    想法可以是复制图例句柄以与标签具有相同的大小

    legend = ['%s (%.1f a day)' %(i, row/7) for i, row in s.iteritems()]
    h,l = ax.get_legend_handles_labels()
    L = ax.legend(handles = h*len(legend), labels=legend, loc='center left', 
                  bbox_to_anchor=(1, 0.5), fontsize=18)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-01
      • 1970-01-01
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多