Reputation: 21
I have plotted a graph with two y-axes with python. However, I would like to have more space between the two lines, with the secondary y-axes on the top of the graph.
here's my code:
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()
Output:
but I would like to have something like this:
Upvotes: 2
Views: 432
Reputation: 4045
Does it suit you to to adjust the limits?
fig, ax1 = plt.subplots()
ax2 = ax1.twinx() # open second y-axis
line1, = ax1.plot([0, 1, 2], [0, 1, 2], "b-", label="Line 1")
line2, = ax2.plot([0, 1, 2,], [10, 13, 12], "r-", label="Line 2")
# set limits
ax2.set_ylim( (-10,14) )
plt.show()
Upvotes: 1
Reputation: 4629
Would a two-subplots setup work for you?
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()
Upvotes: 1