I have a dataframe as the following:
我有一个数据帧如下:
state year SUR index
0 Aguascalientes 1997 1.116118
1 Aguascalientes 1998 1.129570
2 Aguascalientes 1999 1.129570
3 Aguascalientes 2000 1.129570
4 Aguascalientes 2001 1.340662
with 32 different states. I need to plot how has the sur index has evolved over the years and therefore I need 32 different graphs in a single jpg with 4 grafs per row and a total of 8 rows.
有32个不同的州。我需要描绘sur指数多年来如何演变,因此我需要在一个jpg中有32个不同的图形,每行4个grafs,总共8行。
What I tried:
我尝试了什么:
def plotting(df):
pp = PdfPages('multipage.pdf')
for estado in df['state'].unique():
plt.plot(df['year'].unique(),df['SUR index'][df['state']==estado],"b")
plt.ylabel('Sur index')
plt.xlabel('Año')
plt.title(estado)
plt.savefig(pp, format='pdf')
plt.figure()
pp.close()
However, the first states gets all the data from other states and I have 32 different lines in that one. Also, I haven't found a way to have it in the 8*4 way I need it to be.
但是,第一个状态从其他状态获取所有数据,并且在该状态中有32个不同的行。此外,我还没有找到一种方法,以我需要它的8 * 4方式。
1 个解决方案
#1
1
Here is some sample code, for your example you will need to adjust the size of the axes grid (to 8x4).
下面是一些示例代码,您需要调整轴网格的大小(到8x4)。
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.DataFrame()
df['State'] = (['a','b','c','d']*30)
df.sort_values(by='State', inplace=True)
df.reset_index(inplace=True, drop=True)
df['year'] = range(1990, 2020)*4
df['SUR'] = np.random.uniform(0,100,120)
fig, axes = plt.subplots(2,2)
for (name, df), ax in zip(df.groupby('State'), axes.flat):
df.plot(x='year',y='SUR', ax=ax, legend=False)
ax.set_title(name)
fig.tight_layout()
fig.show()
To add labels to the axes you need to call:
要为需要调用的轴添加标签:
ax.set_xlabel(...)
ax.set_ylabel(...)
To save the figure call:
要保存图形调用:
fig.savefig(...)
#1
1
Here is some sample code, for your example you will need to adjust the size of the axes grid (to 8x4).
下面是一些示例代码,您需要调整轴网格的大小(到8x4)。
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.DataFrame()
df['State'] = (['a','b','c','d']*30)
df.sort_values(by='State', inplace=True)
df.reset_index(inplace=True, drop=True)
df['year'] = range(1990, 2020)*4
df['SUR'] = np.random.uniform(0,100,120)
fig, axes = plt.subplots(2,2)
for (name, df), ax in zip(df.groupby('State'), axes.flat):
df.plot(x='year',y='SUR', ax=ax, legend=False)
ax.set_title(name)
fig.tight_layout()
fig.show()
To add labels to the axes you need to call:
要为需要调用的轴添加标签:
ax.set_xlabel(...)
ax.set_ylabel(...)
To save the figure call:
要保存图形调用:
fig.savefig(...)