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

时间:2017-06-11 13:29:44

标签: python pandas matplotlib

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

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

到目前为止,我尝试了一些事情,但显然不是那么容易。

有些人知道我该怎么做吗?

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

      |  G1   |  G2  |
      |-------|------|
index | A  B  | C  D |
------|-------|------|
可能是大熊猫已经可以为我做到这一点。这就是我使用 pandas 标签的原因。

enter image description here

2 个答案:

答案 0 :(得分:5)

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

enter image description here

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

答案 1 :(得分:1)

这是我提出的一个例子。既然你没有提供你的代码,我没有大熊猫就做了,因为我不熟悉它。

你基本上可以绘制一个然后在你以前的所有轴上创建另一个轴,用ax5.axis('off')删除它的轴并在其上绘制2行和文本。

from matplotlib import lines
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 4*np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
y4 = np.cos(x)/(x+1)


fig = plt.figure()
fig.subplots_adjust(hspace=.5)
ax1 = plt.subplot(411)
ax1.plot(x, y1)
ax2 = plt.subplot(412)
ax2.plot(x, y2)
ax3 = plt.subplot(413)
ax3.plot(x, y3)
ax4 = plt.subplot(414)
ax4.plot(x, y4)

# new axis around the others with 0-1 limits
ax5 = plt.axes([0, 0, 1, 1])
ax5.axis('off')

line_x1, line_y1 = np.array([[0.05, 0.05], [0.05, 0.5]])
line1 = lines.Line2D(line_x1, line_y1, lw=2., color='k')
ax5.add_line(line1)

line_x2, line_y2 = np.array([[0.05, 0.05], [0.55, 0.9]])
line2 = lines.Line2D(line_x2, line_y2, lw=2., color='k')
ax5.add_line(line2)

ax5.text(0.0, 0.75, "G1")
ax5.text(0.0, 0.25, "G2")

plt.show()

Resulting image

How to draw a line outside of an axis in matplotlib (in figure coordinates)?启发