Matplotlib-绘制子图中的组合线/条形图 - 无法看到两条线

问题描述 投票:0回答:1

我有一个报告,我正在尝试添加几个子图。使用这个例子,我能够创建一个组合线/条形图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

更新代码我得到了这个:

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 = FuncFormatter(billions)
formatterm = FuncFormatter(millions)


barax = ax2.twinx()





barax.plot(data.index, data['Profit'], linewidth=3, color='#a64dff')


barax.xaxis.tick_top()
barax.yaxis.set_major_formatter(formatterm)
ax2.yaxis.set_major_formatter(formatterb)

ax2.bar(data.index, data['Revenue'], color='blue')

enter image description here

但是你可以看到我试图改变条形尺寸和颜色,但那不起作用?

python pandas matplotlib plot
1个回答
0
投票

我会稍微改变一下。通常我会提前定义我的子图,这使它们更容易引用。

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

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

您可以采用相同的格式进行格式化,只需确保引用正确的AxesSubplot即可。

编辑(Per @DickThompsons评论)

如果要将两个图形叠加到单个图形上,则需要使用双胞胎返回的AxesSubplot进行绘图。

在您的示例中,您使用ax2

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

你应该使用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

© www.soinside.com 2019 - 2024. All rights reserved.