|
17 | 17 | import numpy as np |
18 | 18 | import matplotlib.pyplot as plt |
19 | 19 |
|
20 | | - |
21 | | -def two_scales(ax1, time, data1, data2, c1, c2): |
22 | | - """ |
23 | | -
|
24 | | - Parameters |
25 | | - ---------- |
26 | | - ax : axis |
27 | | - Axis to put two scales on |
28 | | -
|
29 | | - time : array-like |
30 | | - x-axis values for both datasets |
31 | | -
|
32 | | - data1: array-like |
33 | | - Data for left hand scale |
34 | | -
|
35 | | - data2 : array-like |
36 | | - Data for right hand scale |
37 | | -
|
38 | | - c1 : color |
39 | | - Color for line 1 |
40 | | -
|
41 | | - c2 : color |
42 | | - Color for line 2 |
43 | | -
|
44 | | - Returns |
45 | | - ------- |
46 | | - ax : axis |
47 | | - Original axis |
48 | | - ax2 : axis |
49 | | - New twin axis |
50 | | - """ |
51 | | - ax2 = ax1.twinx() |
52 | | - |
53 | | - ax1.plot(time, data1, color=c1) |
54 | | - ax1.set_xlabel('time (s)') |
55 | | - ax1.set_ylabel('exp') |
56 | | - |
57 | | - ax2.plot(time, data2, color=c2) |
58 | | - ax2.set_ylabel('sin') |
59 | | - return ax1, ax2 |
60 | | - |
61 | | - |
62 | 20 | # Create some mock data |
63 | 21 | t = np.arange(0.01, 10.0, 0.01) |
64 | | -s1 = np.exp(t) |
65 | | -s2 = np.sin(2 * np.pi * t) |
| 22 | +data1 = np.exp(t) |
| 23 | +data2 = np.sin(2 * np.pi * t) |
| 24 | + |
| 25 | +fig, ax1 = plt.subplots() |
| 26 | + |
| 27 | +color = 'tab:red' |
| 28 | +ax1.set_xlabel('time (s)') |
| 29 | +ax1.set_ylabel('exp', color=color) |
| 30 | +ax1.plot(t, data1, color=color) |
| 31 | +ax1.tick_params(axis='y', labelcolor=color) |
66 | 32 |
|
67 | | -# Create axes |
68 | | -fig, ax = plt.subplots() |
69 | | -ax1, ax2 = two_scales(ax, t, s1, s2, 'r', 'b') |
| 33 | +ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis |
70 | 34 |
|
| 35 | +color = 'tab:blue' |
| 36 | +ax2.set_ylabel('sin', color=color) # we already handled the x-label with ax1 |
| 37 | +ax2.plot(t, data2, color=color) |
| 38 | +ax2.tick_params(axis='y', labelcolor=color) |
71 | 39 |
|
72 | | -# Change color of each axis |
73 | | -def color_y_axis(ax, color): |
74 | | - """Color your axes.""" |
75 | | - for t in ax.get_yticklabels(): |
76 | | - t.set_color(color) |
77 | | - return None |
78 | | -color_y_axis(ax1, 'r') |
79 | | -color_y_axis(ax2, 'b') |
| 40 | +fig.tight_layout() # otherwise the right y-label is slightly clipped |
80 | 41 | plt.show() |
0 commit comments