matplotlib 循环为每个类别制作子图 [英] matplotlib loop make subplot for each category

查看:35
本文介绍了matplotlib 循环为每个类别制作子图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

推荐答案

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

You got confused between the matplotlib plotting function and the pandas plotting wrapper.
The problem you have is that ax.plot does not have any x or y argument.

在这种情况下,请像 ax.plot(df0 ['Date'],df0 [['y1','y2']])一样调用它,而无需 x ytitle.可能单独设置标题.示例:

In that case, call it like ax.plot(df0['Date'], df0[['y1','y2']]), without x, y and title. Possibly set the title separately. 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)
    ax.plot(df0['Date'], df0[['y1','y2']])
    ax.set_title(c)

plt.tight_layout()
plt.show()

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

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

示例:

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

这篇关于matplotlib 循环为每个类别制作子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆