python - 将 DataFrame 的列设置为 FacetGrid 图形的行

标签 python pandas seaborn facet-grid

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

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)

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

谢谢!

最佳答案

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

关于python - 将 DataFrame 的列设置为 FacetGrid 图形的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56573027/

相关文章:

python - 如何从表中删除记录?

python - 如何从单个列中获取多个列?

python - 根据每个唯一 ID 的最新时间戳过滤数据框

python - 循环中的 Seaborn 图

python - R函数geom_freqpoly在Python中等效于绘制频率多边形

python - 第一行和最后一行将热图图切成两半

python - 相当于 Python 中 Matlab 中的 'ismember' 吗?

python - 如何在 anaconda 上为 python 安装 tesseract

python - PyTorch 中 RNN(nn.LSTM、nn.GRU 等)的输出 h_n 是如何构造的?

python - 同月累计