I got 2 list of y values.
As you can see the the red line in the plot below, the 6 in the y1 tick and 30 in y2 tick need to be at the same horizontal level (or look the same).
Is it possible to achieve this using maplotlib?
list_y1 = [
7.31, 7.30,7.29, 7.29, 7.44, 8.05, 7.46, 7.79, 8.35, 8.95,
8.95, 8.37, 7.51, 8.34, 8.39, 8.41, 8.46, 8.69, 8.52, 8.51,
8.46, 8.97, 9.35, 9.32, 9.24, 9.46, 9.22, 9.16, 9.08, 9.00,
8.82, 8.57, 8.66, 8.79, 8.47, 8.58, 8.62, 8.66, 9.19, 9.20,
9.13, 9.43 ]
list_y2 = [
30.37, 30.51, 30.62, 30.52, 31.31, 33.82, 31.41, 32.78, 35.29, 37.85,
37.85, 35.36, 31.81, 35.35, 35.56, 35.61, 35.94, 36.36, 36.10, 35.81,
35.35, 37.14, 38.49, 38.34, 38.04, 38.90, 37.84, 37.58, 37.25, 36.90,
36.17, 35.12, 35.53, 36.06, 34.73, 35.15, 35.30, 34.64, 36.76, 36.81,
36.54, 37.71 ]
list_x = [
100Q1, 100Q2, 100Q3, 100Q4, 101Q1,101Q2, 101Q3, 101Q4, 102Q1, 102Q2,
102Q3, 102Q4, 103Q1, 103Q2, 103Q3,103Q4, 104Q1, 104Q2, 104Q3, 104Q4,
105Q1, 105Q2, 105Q3, 105Q4, 106Q1,106Q2, 106Q3, 106Q4, 107Q1, 107Q2,
107Q3, 107Q4, 108Q1, 108Q2, 108Q3,108Q4, 109Q1, 109Q2, 109Q3, 109Q4,
110Q1, 110Q2 ]
CodePudding user response:
The simplest way is to set y limits for both axes to be (4, 10)
and (25, 40)
with:
ax1.set_ylim(4, 10)
ax2.set_ylim(25, 40)
Complete Code
import matplotlib.pyplot as plt
from matplotlib import cm
list_y1 = [7.31, 7.30, 7.29, 7.29, 7.44, 8.05, 7.46, 7.79, 8.35, 8.95,
8.95, 8.37, 7.51, 8.34, 8.39, 8.41, 8.46, 8.69, 8.52, 8.51,
8.46, 8.97, 9.35, 9.32, 9.24, 9.46, 9.22, 9.16, 9.08, 9.00,
8.82, 8.57, 8.66, 8.79, 8.47, 8.58, 8.62, 8.66, 9.19, 9.20,
9.13, 9.43]
list_y2 = [30.37, 30.51, 30.62, 30.52, 31.31, 33.82, 31.41, 32.78, 35.29, 37.85,
37.85, 35.36, 31.81, 35.35, 35.56, 35.61, 35.94, 36.36, 36.10, 35.81,
35.35, 37.14, 38.49, 38.34, 38.04, 38.90, 37.84, 37.58, 37.25, 36.90,
36.17, 35.12, 35.53, 36.06, 34.73, 35.15, 35.30, 34.64, 36.76, 36.81,
36.54, 37.71]
list_x = ['100Q1', '100Q2', '100Q3', '100Q4', '101Q1', '101Q2', '101Q3', '101Q4', '102Q1', '102Q2',
'102Q3', '102Q4', '103Q1', '103Q2', '103Q3', '103Q4', '104Q1', '104Q2', '104Q3', '104Q4',
'105Q1', '105Q2', '105Q3', '105Q4', '106Q1', '106Q2', '106Q3', '106Q4', '107Q1', '107Q2',
'107Q3', '107Q4', '108Q1', '108Q2', '108Q3', '108Q4', '109Q1', '109Q2', '109Q3', '109Q4',
'110Q1', '110Q2']
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
cmap = cm.get_cmap('tab10')
ax1.plot(list_x, list_y1, color = cmap(0), linestyle = '--', linewidth = 2)
ax2.plot(list_x, list_y2, color = cmap(0.1), linestyle = '-', linewidth = 2)
plt.setp(ax1.xaxis.get_majorticklabels(), rotation = 90)
ax1.axhline(y = 6, color = 'red', linewidth = 0.5)
ax1.set_ylim(4, 10)
ax2.set_ylim(25, 40)
plt.show()
Plot
A more complicated way is to follow
Since, in any case, you have to set axes limits and since the second way is more complicated, I suggest the first one.