Python matplotlib 循环为每个类别制作子图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46713186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:46:59  来源:igfitidea点击:

matplotlib loop make subplot for each category

pythonmatplotlib

提问by LauraF

I am trying to write a loop that will make a figure with 25 subplots, 1 for each country. My code makes a figure with 25 subplots, but the plots are empty. What can I change to make the data appear in the graphs?

我正在尝试编写一个循环,该循环将生成一个包含 25 个子图的图形,每个国家 1 个。我的代码制作了一个包含 25 个子图的图,但这些图是空的。我可以更改什么才能使数据显示在图表中?

fig = plt.figure()

for c,num in zip(countries, xrange(1,26)):
    df0=df[df['Country']==c]
    ax = fig.add_subplot(5,5,num)
    ax.plot(x=df0['Date'], y=df0[['y1','y2','y3','y4']], title=c)

fig.show()

回答by ImportanceOfBeingErnest

You got confused between the matplotlib plotting function and the pandas plotting wrapper.
The problem you have is that ax.plotdoes not have any xor yargument.

您在 matplotlib 绘图函数和 Pandas 绘图包装器之间感到困惑。
您遇到的问题是ax.plot没有任何xy参数。

Use ax.plot

ax.plot

In that case, call it like ax.plot(df0['Date'], df0[['y1','y2']]), without x, yand title. Possibly set the title separately. Example:

在这种情况下,这样称呼它ax.plot(df0['Date'], df0[['y1','y2']]),没有xytitle。可能单独设置标题。例子:

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

countries = np.random.choice(list("ABCDE"),size=25)
df = pd.DataFrame({"Date" : range(200),
                    'Country' : np.repeat(countries,8),
                    'y1' : np.random.rand(200),
                    'y2' : np.random.rand(200)})

fig = plt.figure()

for c,num in zip(countries, xrange(1,26)):
    df0=df[df['Country']==c]
    ax = fig.add_subplot(5,5,num)
    ax.plot(df0['Date'], df0[['y1','y2']])
    ax.set_title(c)

plt.tight_layout()
plt.show()

enter image description here

在此处输入图片说明

Use the pandas plotting wrapper

使用熊猫绘图包装器

In this case plot your data via df0.plot(x="Date",y =['y1','y2']).

在这种情况下,通过 绘制您的数据df0.plot(x="Date",y =['y1','y2'])

Example:

例子:

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

countries = np.random.choice(list("ABCDE"),size=25)
df = pd.DataFrame({"Date" : range(200),
                    'Country' : np.repeat(countries,8),
                    'y1' : np.random.rand(200),
                    'y2' : np.random.rand(200)})

fig = plt.figure()

for c,num in zip(countries, xrange(1,26)):
    df0=df[df['Country']==c]
    ax = fig.add_subplot(5,5,num)
    df0.plot(x="Date",y =['y1','y2'], title=c, ax=ax, legend=False)

plt.tight_layout()
plt.show()

enter image description here

在此处输入图片说明

回答by armatita

I don't remember that well how to use original subplot system but you seem to be rewriting the plot. In any case you should take a look at gridspec. Check the following example:

我不太记得如何使用原始的子情节系统,但您似乎正在重写情节。在任何情况下,您都应该查看gridspec。检查以下示例:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure()

gs1 = gridspec.GridSpec(5, 5)
countries = ["Country " + str(i) for i in range(1, 26)]
axs = []
for c, num in zip(countries, range(1,26)):
    axs.append(fig.add_subplot(gs1[num - 1]))
    axs[-1].plot([1, 2, 3], [1, 2, 3])

plt.show()

Which results in this:

结果如下:

matplotlib gridspec example

matplotlib gridspec 示例

Just replace the example with your data and it should work fine.

只需用您的数据替换示例,它应该可以正常工作。

NOTE: I've noticed you are using xrange. I've used rangebecause my version of Python is 3.x. Adapt to your version.

注意:我注意到您正在使用xrange. 我使用range是因为我的 Python 版本是 3.x。适应您的版本。