【发布时间】:2017-12-22 03:05:44
【问题描述】:
我有一份报告,我正在尝试添加几个子图。使用这个例子,我能够创建一个组合的线/条图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)
看起来非常简单/标准,但由于某种原因,根据我放置最后两行的顺序,我要么看到利润要么看到收入,而不是两者。
更新代码我得到这个:
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')
但是,正如您所见,我正在尝试更改条形图的大小和颜色,但这不起作用?
【问题讨论】:
标签: python pandas matplotlib plot