matplotlib:两个带两个轴的图表类型

时间:2013-11-20 11:53:59

标签: python charts matplotlib

我想使用matplotlib制作以下图表:

Two chart types with two axes

this example我知道如何制作堆积柱形图。

如何在列顶部绘制一条线(具有相应的辅助轴)?

1 个答案:

答案 0 :(得分:1)

您可以使用普通折线图调用.plot()

稍微修改一下您所引用的示例:

import numpy as np
import matplotlib.pyplot as plt

N = 5
menMeans   = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd     = (2, 3, 4, 1, 2)
womenStd   = (3, 5, 2, 3, 3)
ind = np.arange(N)    # the x locations for the groups
width = 0.35       # the width of the bars: can also be len(x) sequence

fig, ax = plt.subplots()

ax.bar(ind, menMeans,   width, color='r', yerr=womenStd, 
             align='center', label='Woman')

ax.bar(ind, womenMeans, width, color='y', yerr=menStd,
             bottom=menMeans, align='center', label='Men')

ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
ax.set_yticks(np.arange(0,81,10))

ax.plot(np.random.randint(20,50,5), 'o-', lw=2, color='k', label='Line')

ax.legend()

enter image description here

如果要在Matplotlib的示例页面上单独查看'two_scale'示例,则会在同一轴(比例)上绘制线条。