0

Using Matplotlib, I would like to plot two lines in one graph, where both lines have their own axis.

Currently, I have:

x = [3, 5, 7, 9, 10, 11, 13, 15, 17, 19, 20, 21, 23, 25, 27, 30, 35, 40, 45, 50]
y1 = [0.658431,0.702574,0.727149,0.760198,0.746229,0.768321,0.763344,0.764400,0.759935,0.758930,0.769689,0.773518,0.764118,0.780918,0.767377,0.766301,0.779629,0.774025,0.773127,0.782209]
y2 = [0.008676, 0.014630, 0.021286, 0.025562, 0.018247, 0.026771, 0.036187, 0.025633, 0.031402, 0.031140, 0.031333, 0.027820, 0.020359, 0.033351, 0.032603, 0.027474, 0.025250, 0.023103, 0.030988, 0.026503]

plt.plot(x, y1, label = "line 1")
plt.plot(x, y2, label = "line 2")
  
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.title('Y1 and Y2')
  
plt.legend()

Which results in:

enter image description here

However, both lines look relatively flat as they are represented on the same axis and have a different scale. Instead, I would like an y-axis on the left from 0.66 to 0.78 (to represent y1) and I would like an y-axis on the right between 0 and 0.05 (to represent y2). Then, y1's values can be read on the left axis and y2's values can be read on the right axis and the relative changes are illustrated clearer.

How can I do this?

Emil
  • 1,531
  • 3
  • 22
  • 47
  • Does this answer your question? [matplotlib: overlay plots with different scales?](https://stackoverflow.com/questions/7733693/matplotlib-overlay-plots-with-different-scales) – dm2 May 04 '21 at 22:16
  • 1
    I think that you are looking for this https://matplotlib.org/stable/gallery/subplots_axes_and_figures/two_scales.html – rperezsoto May 04 '21 at 22:20

1 Answers1

1

Based on @rperezsoto's comment, I have the following working code:

fig, ax1 = plt.subplots()

color = 'tab:red'
ax1.set_xlabel('x-axis')
ax1.set_ylabel('AUC', color='blue')
ax1.plot(x, y1, color='blue')
ax1.tick_params(axis='y', labelcolor='blue')

ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis

color = 'tab:blue'
ax2.set_ylabel('Standard deviation', color='grey')  # we already handled the x-label with ax1
ax2.plot(x, y2, color='grey')
ax2.tick_params(axis='y', labelcolor='grey')

fig.tight_layout()  # otherwise the right y-label is slightly clipped
plt.title('Y1 and Y2')
plt.show()

enter image description here

Emil
  • 1,531
  • 3
  • 22
  • 47