简体   繁体   English

Matplotlib几个子图和轴

[英]Matplotlib several subplots and axes

I am trying to use matplotlib to plot several subplots, each with 2 y-axis (the values are completely different between the two curves, so I have to plot them in different y-axis) 我正在尝试使用matplotlib绘制多个子图,每个子图具有2个y轴(两条曲线之间的值完全不同,因此我必须将它们绘制在不同的y轴上)

To plot one graph with 2 y-axis I do: 要绘制一个带有2个y轴的图形,我这样做:

fig, ax1 = plt.subplots(figsize=(16, 10))
ax2 = ax1.twinx()
ax1.plot(line1, 'r')
ax2.plot(line2, 'g')

To plot 2 subplots, one with each curve I do: 要绘制2个子图,每条曲线我都做一个:

plt.subplot(2,1,1)
plt.plot(line1, 'r')
plt.subplot(2,1,2)
plt.plot(line2, 'g')

I can't manage to merge the two methods. 我无法合并这两种方法。

I wanted something like: 我想要类似的东西:

fig, ax1 = plt.subplots(figsize=(16, 10))
plt.subplot(2,1,1)
ax2 = ax1.twinx()
ax1.plot(line1, 'r')
ax2.plot(line2, 'g')
plt.subplot(2,1,2)
ax1.plot(line3, 'r')
ax2.plot(line4, 'g')

But this doesn't work, it just shows 2 empty subplots. 但这是行不通的,它只显示2个空子图。

How can I do this? 我怎样才能做到这一点?

You should create your subplots first, then twin the axes for each subplot. 您应该先创建子图,然后再对每个子图的轴进行配对。 It is easier to use the methods contained in the axis object to do the plotting, rather than the high level plot function calls. 使用轴对象中包含的方法进行绘图比使用高级绘图函数调用更容易。

The axes returned by subplots is an array of axes. subplots返回的axes是轴的数组。 If you have only 1 column or 1 row, it is a 1-D array, but if both are greater than 1 it is a 2-D array. 如果只有1列或1行,则为一维数组,但如果两者均大于1,则为2D数组。 In the later case, you need to either .ravel() the axes array or iterate over the rows and then axes in each row. 在后一种情况下,您需要.ravel()轴数组或遍历行,然后遍历每行中的轴。

import numpy as np
import matplotlib.pyplot as plt

# create a figure with 4 subplot axes
fig, axes = plt.subplots(2,2, figsize=(8,8))

for ax_row in axes:
    for ax in ax_row:
        # create a twin of the axis that shares the x-axis
        ax2 = ax.twinx()
        # plot some data on each axis.
        ax.plot(np.arange(50), np.random.randint(-10,10, size=50).cumsum())
        ax2.plot(np.arange(50), 100+np.random.randint(-100,100, size=50).cumsum(), 'r-')

plt.tight_layout()
plt.show()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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