如何在子批次之间添加层次轴以标记组?

2024-06-16 09:34:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一组不同的时间序列,可以分组。E、 g.下图显示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


Tags: 数据标记truepandasindexplot时间原因
2条回答

这是我想出的一个例子。因为你没有提供你的代码,我没有熊猫,因为我不熟练。在

基本上,您可以像这样绘图,然后围绕之前的所有轴创建另一个轴,用ax5.axis('off')删除它的轴,然后在上面绘制两行和文本。在

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)?

可以在绘图中创建其他轴,这些轴跨越两个绘图,但只有一个左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()

相关问题 更多 >