|
3 | 3 | Plots with different scales |
4 | 4 | =========================== |
5 | 5 |
|
6 | | -Demonstrate how to do two plots on the same axes with different left |
| 6 | +Demonstrate how to do two plots on the same axes with different left and |
7 | 7 | right scales. |
8 | 8 |
|
| 9 | +The trick is to use *two different axes* that share the same *x* axis. |
| 10 | +You can use separate `matplotlib.ticker` formatters and locators as |
| 11 | +desired since the two axes are independent. |
9 | 12 |
|
10 | | -The trick is to use *2 different axes*. Turn the axes rectangular |
11 | | -frame off on the 2nd axes to keep it from obscuring the first. |
12 | | -Manually set the tick locs and labels as desired. You can use |
13 | | -separate matplotlib.ticker formatters and locators as desired since |
14 | | -the two axes are independent. |
15 | | -
|
16 | | -This is achieved in the following example by calling the Axes.twinx() |
17 | | -method, which performs this work. See the source of twinx() in |
18 | | -axes.py for an example of how to do it for different x scales. (Hint: |
19 | | -use the xaxis instance and call tick_bottom and tick_top in place of |
20 | | -tick_left and tick_right.) |
| 13 | +Such axes are generated by calling the `Axes.twinx` method. Likewise, |
| 14 | +`Axes.twiny` is available to generate axes that share a *y* axis but |
| 15 | +have different top and bottom scales. |
21 | 16 |
|
22 | 17 | The twinx and twiny methods are also exposed as pyplot functions. |
23 | 18 |
|
|
31 | 26 | s1 = np.exp(t) |
32 | 27 | ax1.plot(t, s1, 'b-') |
33 | 28 | ax1.set_xlabel('time (s)') |
34 | | -# Make the y-axis label and tick labels match the line color. |
| 29 | +# Make the y-axis label, ticks and tick labels match the line color. |
35 | 30 | ax1.set_ylabel('exp', color='b') |
36 | | -for tl in ax1.get_yticklabels(): |
37 | | - tl.set_color('b') |
38 | | - |
| 31 | +ax1.tick_params('y', colors='b') |
39 | 32 |
|
40 | 33 | ax2 = ax1.twinx() |
41 | | -s2 = np.sin(2*np.pi*t) |
| 34 | +s2 = np.sin(2 * np.pi * t) |
42 | 35 | ax2.plot(t, s2, 'r.') |
43 | 36 | ax2.set_ylabel('sin', color='r') |
44 | | -for tl in ax2.get_yticklabels(): |
45 | | - tl.set_color('r') |
| 37 | +ax2.tick_params('y', colors='r') |
| 38 | + |
| 39 | +fig.tight_layout() |
46 | 40 | plt.show() |
0 commit comments