Home > OS >  How to fix the plot using iteration through the subplots by axs.flat?
How to fix the plot using iteration through the subplots by axs.flat?

Time:04-28

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("population.csv")
df["MonthYear"] = df["Month"].map(str)   " "   df["Year"].map(str)
df["MonthYear"] = pd.to_datetime(df["MonthYear"], format="%b %Y")

x = df["MonthYear"]
y = df['Population']

fig, axs = plt.subplots(nrows=2, ncols=2)

for col, ax in zip(df.columns, axs.flatten()):
  ax.plot(x,y)
  ax.set_title(col)
  plt.subplots_adjust(wspace=.5, hspace=.5)

fig.tight_layout()
plt.show()

The code above results to this: https://i.stack.imgur.com/vbCnI.png

How can I make it to this: https://i.stack.imgur.com/rCpHN.png by iterating them using axs.flat

Aside from the plot title problem, how can I use axs.flat to make the expected figure happen?

The csv file contains: (not complete, just for example)

Month,Year,Region,Population

Jan,2008,Region.V,2.953926

Feb,2008,Region.V,2.183336

Jan,2009,Region.V,5.23598

Feb,2009,Region.V,3.719351

Jan,2008,Region.VI,3.232928

Feb,2008,Region.VI,2.297784

Jan,2009,Region.VI,6.231395

Feb,2009,Region.VI,7.493449

CodePudding user response:

you need to change the subplot fig, axs = plt.subplots(nrows=1, ncols=2)

CodePudding user response:

Your problem is not with the axis iteration but plotting with a continuous linestyle a set of points which are not x-axis ordered meaning that the line keeps going left and right, hence adds a lot of noise to the visualization.

Try:

fig, axs = plt.subplots(nrows=2, ncols=2)

for col, ax in zip(df.columns, axs.flatten()): 
  x_order = np.argsort(x)
  ax.plot(x.iloc[x_order],y.iloc[x_order])
  ax.set_title(col)
  plt.subplots_adjust(wspace=.5, hspace=.5)
  • Related