简体   繁体   中英

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:
在此处输入图像描述

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

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()

在此处输入图像描述

You can use matplotlib's matplotlib.axes.Axes.twinx method to add another y axis

# assuming `ax` is the `Axes` instance for the graph using "Age" as y-label

# `ax2` is the `Axes` instance for the second y-axis
ax2 = ax.twinx()

# add label and plot values on `ax2`
ax2.set_ylabel("Depth (cm)")
ax2.plot(depth_data, x_values)  # examples

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM