Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

matplotlib - Create a graph with two y axes and the same x axis/data in Python

I am trying to create a graph which has two y axis (on the same side). One axis is depth (cm) and the other is age (cal BP). There is only one series of data on the graph (ex. Total organic carbon).

I have the data in a txt file and it looks like this:

depth   min max median  mean
0   -66 -60 -63 -63
0.5 -62 -29 -52 -50
1   -60 4   -41 -38
1.5 -58 37  -30 -25
2   -57 71  -20 -13
2.5 -55 105 -9  0
3   -53 138 2   13
3.5 -52 171 13  25
4   -50 204 24  38
4.5 -49 238 34  51
5   -47 271 45  63
5.5 -35 286 59  76
6   -27 301 73  90
6.5 -20 317 88  103
7   -15 330 103 116
7.5 -10 349 117 130
8   -6  370 130 143
8.5 -2  397 143 156
9   2   421 156 169
9.5 6   449 168 183
10  10  479 180 196
10.5    22  489 194 209
11  33  498 208 222
11.5    44  512 220 235
12  52  524 234 249
12.5    61  542 248 262
13  68  558 262 275
13.5    73  579 276 288
14  78  597 288 301
14.5    83  621 301 314
15  88  643 313 328
15.5    104 653 326 341
16  119 663 341 355

I want to use the depth and the mean to create the y axes.
Here is what the output should look like:
enter image description here

I am using python.
Thank you all very much!!!
Cheers,
Lara

question from:https://stackoverflow.com/questions/65929994/create-a-graph-with-two-y-axes-and-the-same-x-axis-data-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To create two y-axes and set the ticks for each, you can use the following code. This example customizes this answer. It also uses a function from the official reference, so please refer to it.

import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator

def make_patch_spines_invisible(ax):
    ax.set_frame_on(True)
    ax.patch.set_visible(False)
    for sp in ax.spines.values():
        sp.set_visible(False)

fig, ax1 = plt.subplots(figsize=(4,9))
fig.subplots_adjust(right=0.75)

x = 1
y = 1
ax2 = ax1.twinx()

ax1.scatter(x,y)
ax1.set_yticks(df.depth)
ax1.yaxis.set_minor_locator(MultipleLocator(0.5))
ax1.set_ylabel('depth')
ax1.spines['top'].set_visible(False)
ax1.spines['right'].set_visible(False)
ax2.set_yticks(df['mean'])
ax2.spines["left"].set_position(("axes", -0.3))
ax2.set_ylabel('mean')
make_patch_spines_invisible(ax2)

ax2.spines["left"].set_visible(True)
ax2.yaxis.set_label_position('left')
ax2.yaxis.set_ticks_position('left')

plt.show()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...