Matplotlib在子图中打印组合的折线图/条形图时不能同时看到这两条线

2024-06-09 12:35:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个报告,我正在尝试添加几个子批次。通过这个例子,我可以创建一个组合的线/条图How to align the bar and line in matplotlib two y-axes chart?

但是,我现在需要将它作为一个子图添加到现有的绘图中(如果有意义的话)。在格式方面,一切都对我有效,但由于某些原因,我不能同时显示行和条,一次只能显示1个。这是我配置的代码,有人能告诉我我做错了什么吗?在

import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8.5,11))
ax2 = plt.subplot2grid((4, 2), (0, 1))

def billions(x, pos):
    'The two args are the value and tick position'
    return '$%1.1fB' % (x*1e-9)

def millions(x, pos):
    'The two args are the value and tick position'
    return '$%1.1fM' % (x*1e-6)

formatterb = plt.FuncFormatter(billions)
formatterm = plt.FuncFormatter(millions)

barax = ax2.twinx()

data = growthtable[['date','total','profit']]

barax.set_ylabel('Total')
ax2.set_ylabel('Profit')

barax.xaxis.tick_top()
barax.yaxis.set_major_formatter(formatterm)
ax2.yaxis.set_major_formatter(formatterb)
barax.set_title('Revenue and Profits')

data['Revenue'].plot(kind='bar',ax=ax2,facecolor='blue')
data['Profit'].plot(ax=ax2)

看起来很简单/标准,但出于某种原因,我根据订单下最后两行,要么看到利润要么看到收入,而不是两者兼而有之。在

enter image description here

enter image description here

更新代码我得到这个:

^{pr2}$

enter image description here

然而,正如你所看到的,我试图改变酒吧的大小和颜色,但这不起作用?在


Tags: andthe代码posdatamatplotlibdefbar
1条回答
网友
1楼 · 发布于 2024-06-09 12:35:30

我会采取稍微不同的方法。通常我会提前定义我的子批次,这样可以更容易地引用它们。在

fig, (ax1, ax1) = plt.subplots(2, sharex=True)

df.profit.plot(ax=ax1)
df.revenue.plot(kind='bar', ax=ax2)

您可以用同样的方式进行格式化,只需确保引用正确的AxesSubplot。在

编辑(根据@dickthompson评论)

如果要将两个图叠加到一个图上,则需要使用twin返回的AxesSubplot进行绘图。在

在您的示例中,您将ax2同时用于:

^{pr2}$

其中一个应使用ax2,另一个使用barax

data['Revenue'].plot(kind='bar',ax=barax, facecolor='blue')
data['Profit'].plot(ax=ax2)

所有其他条件相等,则应创建您描述的图形并将其放置在图形的右上角。这是我创建的一个例子。在

fig = plt.figure()
ax = plt.subplot2grid((4,2), (0,1))
ax2 = ax.twinx()
df.Profit.plot(ax=ax)
df.Revenue.plot(kind='bar', ax=ax2)
ax.yaxis.set_major_formatter(formatterm)
ax2.yaxis.set_major_formatter(formatterb)
fig.show()

enter image description here

相关问题 更多 >