首页 > 解决方案 > 子图的 Matplotlib 对齐/设置垂直空间(Jupyter Notebook)

问题描述

我有 2 个地块堆叠在一起。上图的图例由较大的数字组成,因此该图被推到右侧。我已经看到有一个锚定的概念,但我没有设法实现它。我的想法是对齐左 y 轴。另外,子图之间的空间有点太宽了,有没有办法控制这种行为?

谁能帮帮我?

非常感谢,大家注意安全!

我创建了一些测试数据:

数据

编码:

fig, host = plt.subplots(figsize=(8,4))
plt.title('test')
fig, hos = plt.subplots(figsize=(8,2))

par1 = host.twinx()

p1, = host.plot(df.ExpectedValueEUR, "b-", marker = 'o', label="ExpectedValueEUR")
p2, = par1.plot(df.Count, "r-", label="Count", ls='dotted')
p3, = hos.plot(df.Average, "g-", label="Average", ls='dashed')

host.set_ylim(1000000, 20000000)
par1.set_ylim(5, 100)
hos.set_ylim(0, 1200000)

hos.set_xlabel("Date")
host.set_ylabel("ExpectedValueEUR")
par1.set_ylabel("Count")
hos.set_ylabel("Average")

host.yaxis.label.set_color(p1.get_color())
par1.yaxis.label.set_color(p2.get_color())
hos.yaxis.label.set_color(p3.get_color())

tkw = dict(size=4, width=1.5)
host.tick_params(axis='y', colors=p1.get_color(), **tkw)
par1.tick_params(axis='y', colors=p2.get_color(), **tkw)
hos.tick_params(axis='y', colors=p3.get_color(), **tkw)
host.tick_params(axis='x', **tkw)

line1 = [p1, p2]
line2 = [p3]
host.legend(line1, [l.get_label() for l in line1])
hos.legend(line2, [l.get_label() for l in line2])

host.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))
hos.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))

plt.show()

该图如下所示: 图形

标签: pythonmatplotlibjupyter-notebook

解决方案


推荐阅读