首页 > 解决方案 > 绘制熊猫数据框时缺少 xticklabels 的第一个值

问题描述

我是 Pandas 和 matplotlib 的新手,想绘制这个 DataFrame

      season   won               team  matches    pct_won
0  2008/2009  28.0  Manchester United       38  73.684211
1  2009/2010  27.0  Manchester United       38  71.052632
2  2010/2011  23.0  Manchester United       38  60.526316
3  2011/2012  28.0  Manchester United       38  73.684211
4  2012/2013  28.0  Manchester United       38  73.684211
5  2013/2014  19.0  Manchester United       38  50.000000
6  2014/2015  20.0  Manchester United       38  52.631579
7  2015/2016  19.0  Manchester United       38  50.000000

使用这些代码行:

ax = aggregated_frame.plot(x='season', y='pct_won', figsize=(8,8), marker='o', rot=90, title='Performance by season of Team: {}'.format(aggregated_frame.iloc[0]['team']))
ax.set_xticklabels(aggregated_frame.season)
ax.set_xlabel('')
ax.yaxis.grid()
ax.yaxis.set_major_formatter(mtick.PercentFormatter())
ax.legend(['Percentage of Matches Won'], fontsize=14)
for item in ([ax.title, ax.xaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()):
    item.set_fontsize(14);

但是 my 的第一个值xticklabels在结果图中被删除:

Result_By_Plotting

我尝试了几个选项,甚至只是 set ax.set_xticklabels([1,2,3,4,5,6,7,8]),但每次都删除第一个值。

这里有什么问题?任何帮助都非常受欢迎。

另外:为什么season首先不将值用作标签?如果我省略set_xticklabels了 x 轴上根本没有打印任何标签。

标签: pandasmatplotlib

解决方案


你不应该在没有设置刻度位置的情况下设置标签。即,如果你使用ax.set_xticklabels你总是需要使用ax.set_ticks(否则,可能会有例外,在这种情况下你需要确切地知道你在做什么)。

这里:

ax.set_xticks(range(len(df)))
ax.set_xticklabels(df.season)

生产

在此处输入图像描述


推荐阅读