首页 > 解决方案 > 将 DataFrame 的列设置为 FacetGrid 图形的行

问题描述

我有一个国家面板数据集,其中包含每年国家观察的多个指标。为简单起见,我在这里只报告两个指标:温室气体和空气排放

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)

我该怎么做?循环播放?但这不会覆盖图表吗?

谢谢!

标签: pythonpandasseabornfacet-grid

解决方案


您需要将 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']

推荐阅读