'How to fix the plot using iteration through the subplots?

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("population.csv")

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



Solution 1:[1]

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

Solution 2:[2]

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 = x.argsort()
  ax.plot(x[x_order],y[x_order])
  ax.set_title(col)
  plt.subplots_adjust(wspace=.5, hspace=.5)

It seems to work in my environment when reproducing it on your sample

import matplotlib.pyplot as plt
import pandas as pd

s = """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"""

data = [l.split(',') for l in s.splitlines() if l]
df = pd.DataFrame(data[1:], columns=data[0])
df['Population'] = df['Population'].astype(float)

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()):
    x_order = x.argsort()
    ax.plot(x[x_order],y[x_order])
    ax.set_title(col)
    plt.subplots_adjust(wspace=.5, hspace=.5)

fig.tight_layout()
plt.show()

which produces

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DataSciRookie
Solution 2