英文:
Mutliple plots not showing when using DatetimeIndex
问题
我想创建一个包含线性图和条形图的图形。这段代码只显示我创建的两个图之一:
df = pd.DataFrame({
'abnormal' : [90,40,30,30,30,25,25,20,15,10],
'fix' : [60,70,65,70,70,60,50,45,45,45],
'normal' : [140,160,170,180,190,200,210,220,230,240],
'bad_rate' : [210,100,100,70,70,75,70,60,65,60]})
df.set_index(pd.to_datetime(pd.date_range('2010-01-01', periods=10, freq='Y')), inplace=True)
df['abnormal'].plot(kind='bar')
df['bad_rate'].plot(secondary_y=True)
plt.show()
然而,如果不使用DatetimeIndex,它会正确显示:
df = pd.DataFrame({
'abnormal' : [90,40,30,30,30,25,25,20,15,10],
'fix' : [60,70,65,70,70,60,50,45,45,45],
'normal' : [140,160,170,180,190,200,210,220,230,240],
'bad_rate' : [210,100,100,70,70,75,70,60,65,60]})
# df.set_index(pd.to_datetime(pd.date_range('2010-01-01', periods=10, freq='Y')), inplace=True)
df['abnormal'].plot(kind='bar')
df['bad_rate'].plot(secondary_y=True)
plt.show()
我看不出问题在哪里。
英文:
I want to create a figure with one line plot and a bar plot together. This code doesnt show the 2 plots I am creating (only one of them is displayed):
df = pd.DataFrame({
'abnormal' : [90,40,30,30,30,25,25,20,15,10],
'fix' : [60,70,65,70,70,60,50,45,45,45],
'normal' : [140,160,170,180,190,200,210,220,230,240],
'bad_rate' : [210,100,100,70,70,75,70,60,65,60]})
df.set_index(pd.to_datetime(pd.date_range('2010-01-01', periods=10, freq='Y')), inplace=True)
df['abnormal'].plot(kind='bar')
df['bad_rate'].plot(secondary_y=True)
plt.show()
However, if not using the DatetimeIndex, it shows correctly:
df = pd.DataFrame({
'abnormal' : [90,40,30,30,30,25,25,20,15,10],
'fix' : [60,70,65,70,70,60,50,45,45,45],
'normal' : [140,160,170,180,190,200,210,220,230,240],
'bad_rate' : [210,100,100,70,70,75,70,60,65,60]})
#df.set_index(pd.to_datetime(pd.date_range('2010-01-01', periods=10, freq='Y')), inplace=True)
df['abnormal'].plot(kind='bar')
df['bad_rate'].plot(secondary_y=True)
plt.show()
I can't see what is wrong here.
答案1
得分: 1
以下是您要翻译的内容:
"一种选项是使用年份作为 x 值,然后直接使用 matplotlib 绘制:"
fig, ax = plt.subplots()
ax.bar(df.index.year, df['abnormal'], color='b')
sec_ax = ax.twinx()
sec_ax.plot(df.index.year, df['bad_rate'])
输出:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论