简体   繁体   English

如何在一个循环中绘制多个子图?

[英]How can I plot multiple subplots in a single loop?

Using the code below,使用下面的代码,

import pandas as pd
import matplotlib.pyplot as plt

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

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=9, ncols=2, figsize = (9,19))

for col, ax in zip(df.columns, axs.flatten()):
 ax.plot(x,y)

fig.tight_layout()
plt.show()

Can someone please help me try to figure out how to fix this?有人可以帮我弄清楚如何解决这个问题吗? I'm doing it for days yet I can't figure it out.我做了几天,但我无法弄清楚。

Try this instead:试试这个:

for ax in axs.flatten():
    ax.plot(x,y)

But this of course will plot the same plot in all the subplots.但这当然会在所有子图中绘制相同的图。 I am not sure if you have data for each subplot or you are expecting the same data for all plots.我不确定您是否有每个子图的数据,或者您期望所有图的数据相同。

Update: Lets say you have n columns and you want to make n subplots更新:假设您有 n 列并且您想要制作 n 个子图

x = df["MonthYear"]
column_names = df.columns
n = len(column_names)

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

for i in range(n):
    y = df[column_names[i]]
    axs.flatten()[i].plot(x,y)

Below:以下:

  • create a datetime column and set it as index创建一个日期时间列并将其设置为索引
  • split your dataset according to different possible values for "Region"根据“区域”的不同可能值拆分数据集

-> there is one subplot per Region -> 每个区域有一个子图

EDIT: with real dataset编辑:使用真实数据集

EDIT: the author of the question has removed key informations from their question and deleted their comments.编辑:问题的作者已从他们的问题中删除了关键信息并删除了他们的评论。 So to fully understand this answer:所以要完全理解这个答案:

  • the dataset is from here数据集来自这里
  • in order to remove the last (empty) subplot: you should add fig.delaxes(axs.flat[-1])为了删除最后一个(空的)子图:你应该添加fig.delaxes(axs.flat[-1])
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('denguecases.csv')

df['Date'] = pd.to_datetime(df.apply(lambda row: row.Month + ' ' +  str(row.Year), axis=1))
df.set_index('Date', inplace=True)

fig, axs = plt.subplots(nrows=9, ncols=2, figsize = (9,19))
for region, ax in zip(df.Region.unique(), axs.flat):
    ax.plot(df.query('Region == @region').Dengue_Cases)
    ax.tick_params(axis='x', labelrotation = 45)
    ax.set_title(region)
fig.tight_layout()

有数据集

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

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