matplotlib 用 twinx
画多 y 轴参考 [1]。现想在画图例时,多个 y 轴的图例画在一起,写法参考 [2]。本文展示一个简例,效果:
Code
- 要手动指定颜色,否则原 y 轴的用色和新 y 轴会重合。
import matplotlib.pyplot as plt
# data to plot
a = [
11859.886474338155, 11384.541612887142, 11314.948867713461, 12156.365013852563, 12404.976775275885,
11621.437786082668, 12795.74640426193, 12993.03181918637, 12501.512233289674, 11350.26629984073,
11590.587334446433, 11441.306187592794, 11404.947051407049, 11629.51842160388, 11763.034209161266,
11126.219136054518, 11400.792280787551, 11272.906832672033, 11395.597850760485, 11358.659841616076,
11379.374326229647, 11365.605541074778, 11396.632268102992, 11331.323431712111, 11332.266958200318,
11363.32044026967, 11377.021840279784, 11323.601868202895, 11371.723693824233, 11225.02356255239,
11257.400865610576, 11282.550566847438, 11260.885444273175, 11283.283264922617, 11270.689144877966,
11252.21701350545, 11260.053691403413, 11253.275771074057, 11263.247947131156, 11291.757634932797,
11292.976376828668, 11293.690639328725, 11288.613833603356, 11289.25777231545, 11287.238411511518,
11287.257483993126, 11285.254494562952, 11296.294510594862, 11292.110325229343, 11289.720358617116
]
b = [
0.8172, 0.8354, 0.8223, 0.8213, 0.8197,
0.8052, 0.7974, 0.8086, 0.8036, 0.7972,
0.806, 0.807, 0.7959, 0.7969, 0.8036,
0.7705, 0.7851, 0.7811, 0.7788, 0.7765,
0.7832, 0.7816, 0.784, 0.7802, 0.78,
0.7805, 0.7788, 0.7779, 0.7831, 0.7767,
0.7782, 0.7791, 0.778, 0.7787, 0.7788,
0.7781, 0.7783, 0.7776, 0.7779, 0.779,
0.7791, 0.7791, 0.779, 0.7791, 0.7789,
0.7788, 0.7788, 0.779, 0.7788, 0.7788
]
assert len(a) == len(b)
fig, ax = plt.subplots()
# 1st y-axis
ln1 = plt.plot(range(len(a)), a, label='a', c='r') # 手动指定颜色,否则可能两线同色
ax.ticklabel_format(style='sci', scilimits=(0,3), axis='y')
ax.set_ylabel('a')
ax.set_xlabel('x')
# 2nd y-axis
zax = ax.twinx()
ln2 = zax.plot(range(len(b)), b, label='b', c='g') # 手动指定颜色,否则可能两线同色
zax.set_ylabel('b')
# legend
lines = ln1 + ln2
labels = [l.get_label() for l in lines]
ax.legend(lines, labels, fancybox=True, framealpha=0)
plt.title("multiple y-axes one legend")
fig.tight_layout()
fig.savefig("test.png", bbox_inches="tight")
References
- 【python】matplotlib 实现双(多)Y轴图
- Secondary axis with twinx(): how to add to legend
- matplotlib刻度值使用科学记数法