File: two_scales.py

package info (click to toggle)
matplotlib 3.10.1%2Bdfsg1-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 78,340 kB
  • sloc: python: 147,118; cpp: 62,988; objc: 1,679; ansic: 1,426; javascript: 786; makefile: 92; sh: 53
file content (57 lines) | stat: -rw-r--r-- 1,619 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"""
===========================
Plots with different scales
===========================

Two plots on the same Axes with different left and right scales.

The trick is to use *two different Axes* that share the same *x* axis.
You can use separate `matplotlib.ticker` formatters and locators as
desired since the two Axes are independent.

Such Axes are generated by calling the `.Axes.twinx` method. Likewise,
`.Axes.twiny` is available to generate Axes that share a *y* axis but
have different top and bottom scales.
"""
import matplotlib.pyplot as plt
import numpy as np

# Create some mock data
t = np.arange(0.01, 10.0, 0.01)
data1 = np.exp(t)
data2 = np.sin(2 * np.pi * t)

fig, ax1 = plt.subplots()

color = 'tab:red'
ax1.set_xlabel('time (s)')
ax1.set_ylabel('exp', color=color)
ax1.plot(t, data1, color=color)
ax1.tick_params(axis='y', labelcolor=color)

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

color = 'tab:blue'
ax2.set_ylabel('sin', color=color)  # we already handled the x-label with ax1
ax2.plot(t, data2, color=color)
ax2.tick_params(axis='y', labelcolor=color)

fig.tight_layout()  # otherwise the right y-label is slightly clipped
plt.show()

# %%
#
# .. admonition:: References
#
#    The use of the following functions, methods, classes and modules is shown
#    in this example:
#
#    - `matplotlib.axes.Axes.twinx` / `matplotlib.pyplot.twinx`
#    - `matplotlib.axes.Axes.twiny` / `matplotlib.pyplot.twiny`
#    - `matplotlib.axes.Axes.tick_params` / `matplotlib.pyplot.tick_params`
#
# .. tags::
#
#    component: axes
#    plot-type: line
#    level: beginner