如何在子图上添加分层轴以标记组?

dis*_*ame 1 python matplotlib pandas

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

我想在图中通过在左侧添加另一个轴来反映这一点,该轴穿过涡轮组并相应地标记轴.

到目前为止,我尝试过一些东西,但显然不是那么容易.

有些人知道我怎么做吗?

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

      |  G1   |  G2  |
      |-------|------|
index | A  B  | C  D |
------|-------|------|
Run Code Online (Sandbox Code Playgroud)

可能是大熊猫已经可以为我做到这一点.这就是我使用pandas标签的原因.

在此输入图像描述

Imp*_*est 5

您可以在绘图中创建其他轴,这两个轴跨越每两个图,但只有左侧y轴,没有刻度和其他装饰.只设置了ylabel.这将使整个事物看起来很好地对齐.

在此输入图像描述

好处是你可以使用你现有的熊猫情节.缺点是超过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()
Run Code Online (Sandbox Code Playgroud)