简体   繁体   中英

Merge two Matplotlib plots having different ranges for the Y-Axis into one plot such that the shapes of the individual plots remain the same

I want to put my two plots into one plot without changing their shape. They have a very different y range. Here are my two plots (I get them when I run the corresponding line of code for the plot) :

Plot 1:

地块 1

Plot 2:

地块 2

When I try plotting both of them onto the same graph, I get :

Plot 3:

地块 3

The plots end up losing their original shape. I'm assuming this is happening because the ranges of y used in both the plots is not the same. These are the data values I used to plot :

y1 = [3.3549674089380157, 3.3549674741748685, 3.354967474135432, 3.3549674741683244, 3.354967802849705] 
y2 = [2.273429505964899, 2.273429556154414, 2.2734295561240736, 2.2734295561482813, 2.2734297980416596]
x = [-16.0, -13.0, -10.0, -6.0, -2.0]

You can use ax.twinx() to create a secondary Y-axis on the right-hand side, then plot each line independently:

import matplotlib.pyplot as plt

x = [-16.0, -13.0, -10.0, -6.0, -2.0]
y1 = [3.3549674089380157, 3.3549674741748685, 3.354967474135432, 3.3549674741683244, 3.354967802849705]
y2 = [2.273429505964899, 2.273429556154414, 2.2734295561240736, 2.2734295561482813, 2.2734297980416596]

fig, ax_left = plt.subplots()
ax_left.plot(x, y1, label='y1', color='green')
ax_left.set_ylabel('y1')

ax_right = ax_left.twinx()
ax_right.plot(x, y2, label='y2', color='orange')
ax_right.set_ylabel('y2')

plt.show()

output:

在此处输入图片说明

Note that since both lines have basically the same shape, they overlap when plotted individually on each axis - but both lines are there with their "original" shape preserved. I've tried to make this a bit clearer by using different colors and labeling each Y-axis.

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