0

I have a numpy array of shape (2,2,1000) representing income-groups, age-groups and a sample of 1000 observations for each group.

I am trying to use a for-loop to plot the 4 combinations of values:

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

so the end result would be 4 separate plots next to each other where the x and y axes change based on the list above. My problem is that I get all 4 plots printed on the same graph. How can I put them on separate graphs?

Here is my code:

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()
Stata_user
  • 562
  • 3
  • 14
  • 2
    This might help: https://stackoverflow.com/questions/31726643/how-to-plot-in-multiple-subplots – BehRouz Mar 27 '23 at 15:58

1 Answers1

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

I'm not sure that you want to plot elasticity[:,j,:] vs elasticity[i,:,:]

enter image description here

gboffi
  • 22,939
  • 8
  • 54
  • 85