|
13 | 13 | Such axes are generated by calling the `Axes.twinx` method. Likewise,
|
14 | 14 | `Axes.twiny` is available to generate axes that share a *y* axis but
|
15 | 15 | have different top and bottom scales.
|
16 |
| -
|
17 |
| -The twinx and twiny methods are also exposed as pyplot functions. |
18 |
| -
|
19 | 16 | """
|
20 |
| - |
21 | 17 | import numpy as np
|
22 | 18 | import matplotlib.pyplot as plt
|
23 | 19 |
|
24 |
| -fig, ax1 = plt.subplots() |
| 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 | +# Create some mock data |
25 | 63 | t = np.arange(0.01, 10.0, 0.01)
|
26 | 64 | s1 = np.exp(t)
|
27 |
| -ax1.plot(t, s1, 'b-') |
28 |
| -ax1.set_xlabel('time (s)') |
29 |
| -# Make the y-axis label, ticks and tick labels match the line color. |
30 |
| -ax1.set_ylabel('exp', color='b') |
31 |
| -ax1.tick_params('y', colors='b') |
32 |
| - |
33 |
| -ax2 = ax1.twinx() |
34 | 65 | s2 = np.sin(2 * np.pi * t)
|
35 |
| -ax2.plot(t, s2, 'r.') |
36 |
| -ax2.set_ylabel('sin', color='r') |
37 |
| -ax2.tick_params('y', colors='r') |
38 | 66 |
|
39 |
| -fig.tight_layout() |
| 67 | +# Create axes |
| 68 | +fig, ax = plt.subplots() |
| 69 | +ax1, ax2 = two_scales(ax, t, s1, s2, 'r', 'b') |
| 70 | + |
| 71 | + |
| 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 | 80 | plt.show()
|
0 commit comments