python - 将 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)
我该怎么做?循环播放?但这不会覆盖图表吗?
谢谢!
解决方案
您需要将 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 - 新手:因为我在范围内不增加
- python - sklearn 和从头开始的不同 Kmean 结果
- reactjs - useEffect 仅适用于第一次更新/渲染
- matlab - 如何解锁 Simulink 库以使其可编辑?
- javascript - 悬停时的高效 JS 事件监听器
- c - 如果在块中引用了具有内部链接的变量,我是否需要在该块中使用 extern 关键字?
- python - 用 scapy 关闭 pcap 文件
- php - 我正在尝试使用“干预\图像库”保存图像。我发现一个错误图像源不可读
- python - 如何使用 tkinter for python 使用自定义字体打印 list = ['a','b','c']
- visual-studio-2019 - 在 Visual Studio 2019 中发布不工作