将DataFrame的列设置为FacetGrid figu的行

2024-09-21 03:22:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个国家小组数据集,其中有每年国家观察的若干指标。为了简单起见,我这里只报告两个指标:温室气体和空气排放

rs = np.random.RandomState(4)
pos = rs.randint(-1, 2, (4, 5)).cumsum(axis=1)
pos -= pos[:, 0, np.newaxis]
pos2 = rs.randint(-4, 3, (4, 5)).cumsum(axis=1)
pos2 -= pos[:, 0, np.newaxis]
year = np.tile(range(5), 4)
walk = np.repeat(range(4), 5)

df = pd.DataFrame(np.c_[pos.flat, pos2.flat, year, walk],
                  columns=["Air emissions", 'GHG', "year", "Country ID"])

我想开发一个可视化,显示每个国家每年每个指标的趋势。每个指标显示在一行中,而国家是我的列。到目前为止,这是我为一个指标——空气排放——所做的工作,但我还想展示温室气体的趋势(以及这里没有报告的其他指标),并将它们添加到空气排放:如何?你知道吗

sns.set(style="ticks")

    # Initialize a grid of plots with an Axes for each walk
grid = sns.FacetGrid(df, col="Country ID", hue="year", palette="tab20c",
                         col_wrap=4, height=3)

    # Draw a line plot to show the trajectory of each random walk
grid.map(plt.plot, "year", "Air emissions",  marker="o")

    # Adjust the arrangement of the plots
grid.fig.tight_layout(w_pad=1)

我该怎么做?循环?但这不会覆盖图表吗?你知道吗

谢谢!你知道吗


Tags: ofthepos报告np国家指标year
1条回答
网友
1楼 · 发布于 2024-09-21 03:22:32

您需要将FacetGrid行中所需的变量编码为一列,其中一列包含每个变量的值。可能不是最好的解释,但看起来是这样的:

    year  Country ID       variable  value
0      0           0  Air emissions      0
1      0           0            GHG      0
2      0           1  Air emissions      0
3      0           1            GHG     -3
4      0           2  Air emissions      0
5      0           2            GHG     -2
...

然后可以将FacetGrid参数row设置为'variable'(还必须删除col_wrap):

grid = sns.FacetGrid(x, row='variable', col="Country ID", hue="year", palette="tab20c", height=3)
grid.map(plt.plot, "year", "value",  marker="o")

您可以使用pivot_table重新格式化数据帧:

df = df.pivot_table(index=['year', 'Country ID'], values=['Air emissions', 'GHG']).stack().reset_index()
df.columns = ['year', 'Country ID', 'variable', 'value']

相关问题 更多 >

    热门问题