python - 如何跨子图添加层次轴以标记组?

标签 python pandas matplotlib

我有一组可以分组的不同时间序列。例如。下图显示了系列 A、B、C 和 D。但是,A 和 B 在组 G1 中,而 C 和 D 在组 G2 中。

我想在图中通过在左侧添加另一个轴来反射(reflect)这一点,该轴穿过涡轮机组并相应地标记这些轴。

到目前为止,我已经尝试了一些东西,但显然其中一个并不那么容易。

有人知道我该怎么做吗?

PS: 因为我在一个已经有列的数据框上使用 Pandas 的plot(subplots=True)

      |  G1   |  G2  |
      |-------|------|
index | A  B  | C  D |
------|-------|------|

pandas 可能已经为我做到了。这就是我使用 pandas 的原因 标签。

enter image description here

最佳答案

您可以在图中创建额外的轴,它跨越每两个图,但只有一个左侧的 y 轴,没有刻度和其他装饰。只设置了一个 ylabel。这将使整个事情看起来很协调。

enter image description here

好处是您可以使用现有的 pandas plot。缺点是多了15行代码。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec


df = pd.DataFrame(np.random.rand(26,4), columns=list("ABCD"))
axes = df.plot(subplots=True)
fig = axes[0].figure


gs = gridspec.GridSpec(4,2)
gs.update(left=0.1, right=0.48, wspace=0.05)
fig.subplots_adjust(left=.2)

for i, ax in enumerate(axes):
    ax.set_subplotspec(gs[i,1])

aux1 = fig.add_subplot(gs[:2,0])
aux2 = fig.add_subplot(gs[2:,0])

aux1.set_ylabel("G1")
aux2.set_ylabel("G2")

for ax in [aux1, aux2]:
    ax.tick_params(size=0)
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.set_facecolor("none")
    for pos in ["right", "top", "bottom"]:
        ax.spines[pos].set_visible(False)
    ax.spines["left"].set_linewidth(3)
    ax.spines["left"].set_color("crimson")


plt.show()

关于python - 如何跨子图添加层次轴以标记组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44484391/

相关文章:

python - 在另一个单元格中的plot()之后未渲染AxesSubplot

python - 使用不带动画功能的 matplotlib 进行动画处理

python - 在 Python Spyder 交互式绘图中。如何链接图以便当我放大图时它会放大其余图

python - 日志记录和 CherryPy 可以共享相同的配置文件吗?

python - 尝试理解 Python 中的可选参数、列表参数和命名参数

python - 将一系列字符串(加上数字)写入一行 csv

Python:将列标题转换为单列值

没有大量库依赖的 Python 消息框

python - 如何在没有索引的 Pandas 中转置数据框?

python - 返回 Pandas 中组/多索引的前 n 个值