多个图表在使用DatetimeIndex时未显示。

huangapple go评论58阅读模式
英文:

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'])

输出:

多个图表在使用DatetimeIndex时未显示。

英文:

One option is to use the year as the x-values and plot directly from 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'])

Output:

多个图表在使用DatetimeIndex时未显示。

huangapple
  • 本文由 发表于 2023年6月29日 22:54:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76582233.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定