python - 增加辅助 y 轴和 x 轴之间的间距?

标签 python matplotlib graph

我用 python 绘制了一个带有两个 y 轴的图。不过,我希望两条线之间有更多空间,辅助 y 轴位于图表顶部。

这是我的代码:

x = data['Data'].tolist() 
y = data['Excess Return'].tolist()
z=data['EPU shock'].tolist()

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
curve1 = ax1.plot(x, y, label='Excess Return', color='r')
curve2 = ax2.plot(x, z, label='EPU shock', color='b')

lines_1, labels_1 = ax1.get_legend_handles_labels()
lines_2, labels_2 = ax2.get_legend_handles_labels()
lines = lines_1 + lines_2
labels = labels_1 + labels_2
ax1.legend(lines, labels, loc="lower center", borderaxespad=-5, ncol=2)
plt.title("European Union")
plt.show()

输出:

Graph 1

但我想要这样的东西:

Graph

最佳答案

两个子图设置适合您吗?

enter image description here

import matplotlib.pyplot as plt
import numpy as np

# Dummy data.
x = np.arange(2000, 2020, 1)
y1 = np.sin(x)
y2 = np.cos(x/2)

# We create a two-subplots figure and hide the boundary between the two Axes.
fig, (ax1, ax_temporary) = plt.subplots(2, 1)
ax2 = ax_temporary.twinx()
for spine in (ax1.spines["bottom"], ax_temporary.spines["top"], ax2.spines["top"]):
    spine.set_visible(False)
ax1.xaxis.set_visible(False)
ax_temporary.yaxis.set_visible(False)
fig.subplots_adjust(hspace=0) # No space left!

# Create curves and legend.
curve1, = ax1.plot(x, y1, label='Excess Return', color='r')
curve2, = ax2.plot(x, y2, label='EPU shock', color='b')
lines_1, labels_1 = ax1.get_legend_handles_labels()
lines_2, labels_2 = ax2.get_legend_handles_labels()
lines = lines_1 + lines_2
labels = labels_1 + labels_2
ax2.legend(lines, labels, loc="lower center", borderaxespad=-5, ncol=2) # Legend on ax2 instead of ax1.

ax1.set_title("European Union")
fig.show()

关于python - 增加辅助 y 轴和 x 轴之间的间距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65089329/

相关文章:

Python:通过 SSH 发送按键事件

Python - 在每个绘图的多个绘图中添加颜色条

python - scipy.integrate.ode 的内部工作

r - 为什么networkd3 R中的forceNetwork显示不在边缘列表中的所有节点?

c++ - BGL : adjacency list returns wrong edge property for descriptor

python - 如何将 dict 转换为 unicode JSON 字符串?

python - 将背景图像添加到 3d 图

python - regplot() 的稳健选项到底有什么作用?

python - 在matplotlib中自动缩写长度字符串

c++ - 在 BOOST 图中找到给定 2 个顶点的多条边