matplotlib 在Python中使用for循环绘图

m1m5dgzv  于 2023-03-30  发布在  Python
关注(0)|答案(1)|浏览(119)

我有一个numpy数组的形状(2,2,1000)代表收入组,年龄组和1000个观察样本每组。
我尝试使用for循环来绘制4个值的组合:

1. < 18 age, i0 income
 2. < 18 age, i1 income
 3. >= 18 age, i0 income
 4. >= 18 age, i1 income

因此,最终结果将是4个相邻的独立图,其中x和y轴根据上面的列表进行更改。我的问题是,我将所有4个图打印在同一个图形上。我如何将它们放在单独的图形上?
下面是我的代码:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

elasticity = np.random.rand(2,2,1000)
print(elasticity.shape)

income = ['i0','i1']
age_gr= ['<=18','>18']

for i in range(len(age_gr)):
    for j in range((len(income))):
        plt.plot(elasticity[:,j,:], elasticity[i,:,:])
        plt.subplot(i,j)
plt.show()
wgx48brx

wgx48brx1#

...
fig, axes = plt.subplots(2, 2, figsize=(8,6), layout='constrained')

for ij, ax in enumerate(axes.flat):
    i, j = ij%2, ij//2
    # below I take the liberty of plotting less stuff, to unclutter the graph
    ax.plot(elasticity[:,j,:8], elasticity[i,:,:8] )
    ax.set_title("Income class: %s; age group: %s"%(income[i], age_gr[j]))
plt.show()

我不确定您是否要绘制elasticity[:,j,:]elasticity[i,:,:]的关系图

相关问题