熊猫DataFrame.value_countsplotbar和DataFrame.value_countscumsumplot不在同一轴上

问题描述

我正在尝试在同一幅图中绘制频率条形图和累积的“误差”。如果我分别绘制它们,则两者都显示为OK,但是在同一图中显示时,累积的图形将显示为已偏移。在使用的代码下方。

df = pd.DataFrame({'Correctas': [4,6,5,4,7,2,8,3,9,10,11,12,6]});

df['Correctas'].value_counts(sort = False).plot.bar();
df['Correctas'].value_counts(sort = False).cumsum().plot();

plt.show()

频率数据是

2      1
3      3
4      7
5     14
6     20
7     24
8     27
9     29
10    30
11    31
12    32

因此,累积量应从2开始,在x轴上应从4开始。

image showing the error

解决方法

这与绘制分类X轴的条形图有关。快速解决方法:

df = pd.DataFrame({'Correctas': [4,6,5,4,7,2,8,3,9,10,11,12,6]});

df_counts = df['Correctas'].value_counts(sort = False)
df_counts.index = df_counts.index.astype('str')

df_counts.plot.bar(alpha=.8);
df_counts.cumsum().plot(color='k',kind='line');

plt.show();

输出:

enter image description here