Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b078a19

Browse files
authored
Merge pull request #7831 from dstansby/two-scales-wrapper
Function wrapper for examples/api/two_scales.py
2 parents 9edcb03 + 213403f commit b078a19

File tree

1 file changed

+56
-16
lines changed

1 file changed

+56
-16
lines changed

examples/api/two_scales.py

Lines changed: 56 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -13,28 +13,68 @@
1313
Such axes are generated by calling the `Axes.twinx` method. Likewise,
1414
`Axes.twiny` is available to generate axes that share a *y* axis but
1515
have different top and bottom scales.
16-
17-
The twinx and twiny methods are also exposed as pyplot functions.
18-
1916
"""
20-
2117
import numpy as np
2218
import matplotlib.pyplot as plt
2319

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
2563
t = np.arange(0.01, 10.0, 0.01)
2664
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()
3465
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')
3866

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')
4080
plt.show()

0 commit comments

Comments
 (0)