[英]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).我正在尝试创建一个具有两个 y 轴(在同一侧)的图形。 One axis is depth (cm) and the other is age (cal BP).
一个轴是深度 (cm),另一个是年龄 (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:我有一个txt文件中的数据,它看起来像这样:
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.我想使用深度和平均值来创建 y 轴。
Here is what the output should look like:这是 output 的外观:
I am using python.我正在使用 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.要创建两个 y 轴并为每个轴设置刻度,您可以使用以下代码。 This example customizes this answer .
此示例自定义此答案。 It also uses a function from the official reference , so please refer to it.
它还使用了官方参考中的function,请参考。
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您可以使用 matplotlib 的
matplotlib.axes.Axes.twinx
方法添加另一个 y 轴
# 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.