python plot two lines with different y axis

Solutions on MaxInterview for python plot two lines with different y axis by the best coders in the world

showing results for - "python plot two lines with different y axis"
Francisco
02 Sep 2017
1import numpy as np
2import matplotlib.pyplot as plt
3
4t = np.arange(0.01, 10.0, 0.01)
5data1 = np.exp(t)
6data2 = np.sin(2 * np.pi * t)
7
8fig, ax1 = plt.subplots()
9
10color = 'tab:red'
11ax1.set_xlabel('time (s)')
12ax1.set_ylabel('exp', color=color)
13ax1.plot(t, data1, color=color)
14ax1.tick_params(axis='y', labelcolor=color)
15
16ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis
17
18color = 'tab:blue'
19ax2.set_ylabel('sin', color=color)  # we already handled the x-label with ax1
20ax2.plot(t, data2, color=color)
21ax2.tick_params(axis='y', labelcolor=color)
22
23fig.tight_layout()  # otherwise the right y-label is slightly clipped
24plt.show()