|  | 
| 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 |  | -    Parameters | 
| 24 |  | -    ---------- | 
| 25 |  | -    ax1 : axis | 
| 26 |  | -        Axis to share a second scale with. | 
| 27 |  | -
 | 
| 28 |  | -    time : array-like | 
| 29 |  | -        x-axis values for both datasets. | 
| 30 |  | -
 | 
| 31 |  | -    data1, data2: array-like | 
| 32 |  | -        Data for respectively the left and the right hand scale. | 
| 33 |  | -
 | 
| 34 |  | -    c1, c2 : color | 
| 35 |  | -        Color for respectively the left and the right hand scale. | 
| 36 |  | -
 | 
| 37 |  | -    Returns | 
| 38 |  | -    ------- | 
| 39 |  | -    ax1, ax2 : tuple of axis instances | 
| 40 |  | -        Respectively the original axis and its new twin axis. | 
| 41 |  | -
 | 
| 42 |  | -    """ | 
| 43 |  | -    ax2 = ax1.twinx()  # create a second axes that shares the same x-axis | 
| 44 |  | - | 
| 45 |  | -    for ax, data, c in ((ax1, data1, c1), (ax2, data2, c2)): | 
| 46 |  | -        ax.plot(time, data, color=c) | 
| 47 |  | -        # Color the y-axis (both label and tick labels) | 
| 48 |  | -        ax.yaxis.label.set_color(c) | 
| 49 |  | -        for t in ax.get_yticklabels(): | 
| 50 |  | -            t.set_color(c) | 
| 51 |  | - | 
| 52 |  | -    return ax1, ax2 | 
| 53 |  | - | 
| 54 | 20 | # Create some mock data | 
| 55 | 21 | t = np.arange(0.01, 10.0, 0.01) | 
| 56 |  | -s1 = np.exp(t) | 
| 57 |  | -s2 = np.sin(2 * np.pi * t) | 
|  | 22 | +data1 = np.exp(t) | 
|  | 23 | +data2 = np.sin(2 * np.pi * t) | 
|  | 24 | + | 
|  | 25 | +# Create twin axes and plot the mock data onto them | 
|  | 26 | +fig, ax1 = plt.subplots() | 
|  | 27 | +ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis | 
| 58 | 28 | 
 | 
| 59 |  | -# Create axes and plot the mock data onto them | 
| 60 |  | -fig, ax = plt.subplots() | 
| 61 |  | -ax1, ax2 = two_scales(ax, t, s1, s2, 'r', 'b') | 
|  | 29 | +for ax, data, c in ((ax1, data1, "red"), (ax2, data2, "blue")): | 
|  | 30 | +    ax.plot(t, data, color=c) | 
|  | 31 | +    # Color the y-axis (both label and tick labels) | 
|  | 32 | +    ax.yaxis.label.set_color(c) | 
|  | 33 | +    for tl in ax.get_yticklabels(): | 
|  | 34 | +        tl.set_color(c) | 
| 62 | 35 | 
 | 
| 63 | 36 | # Label both axes | 
| 64 | 37 | ax1.set_xlabel('time (s)') | 
| 65 | 38 | ax1.set_ylabel('exp') | 
| 66 | 39 | ax2.set_ylabel('sin')  # NB: we already took care of the x-label with ax1 | 
| 67 | 40 | 
 | 
| 68 |  | -fig.tight_layout()  # otherwise the y-labels are slightly clipped | 
|  | 41 | +fig.tight_layout()  # otherwise the right y-label is slightly clipped | 
| 69 | 42 | plt.show() | 
0 commit comments