python - 在 matplotlib 中跨子图绘制分界线

标签 python pandas numpy matplotlib graph

我被要求生成一些用于多基线研究设计的图表,这是一种特殊类型的图表。我把它作为一个机会来学习更多的 Matplotlib 和 Pandas,但我挣扎的一件事是划分 BASE 和 INTERVENTION 的分界线。我需要它继续通过多个子图并很好地扩展。有没有办法完成这样的事情?我曾尝试使用 Lines.Line2D 和 ConnectionPatch 进行试验,但我坚持正确缩放和确定位置。
到目前为止我的(简单)代码。

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

y = np.array([0,1,2,3,4])
fig, axs = plt.subplots(3, sharex=True, sharey=True)
fig.suptitle("I1 - Reakce na změnu prvku")
axs[0].plot(df.index,df['A'], color='lightblue', label="A")
axs[1].plot(df.index,df['N'], color='darkblue', label="N")
axs[2].plot(df.index,df['P'], color='blue', label="P")

plt.yticks(np.arange(y.min(), y.max(), 1))
plt.show()
到目前为止我的情节(上面代码的结果):
My current graph
上下文的示例图:
Sample Multiple Baseline Design graph

最佳答案

我的直觉,对于这种问题是在图形坐标中画一条线。我遇到的一个问题是找到连续轴之间中心区域的位置。我的代码很难看,但它可以工作,并且与每个轴的相对大小或轴之间的间距无关,如下所示:

from matplotlib.lines import Line2D
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    from itertools import zip_longest
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)




xconn = [0.15, 0.35, 0.7]  # position of the vertical lines in each subplot, in data coordinates


fig, axs = plt.subplots(3,1, gridspec_kw=dict(hspace=0.6, height_ratios=[2,0.5,1]))



#
# Draw the separation line, should be done at the very end when the limits of the axes have been set etc.
#
# convert the value of xconn in each axis to figure coordinates
xconn = [fig.transFigure.inverted().transform(ax.transData.transform([x,0]))[0] for x,ax in zip(xconn,axs)]
yconn = []  # y-values of the connecting lines, in figure coordinates
for ax in axs:
    bbox = ax.get_position()
    yconn.extend([bbox.y1, bbox.y0])
# replace each pairs of values corresponding to the bottom and top of each pairs of axes by the average
yconn[1:-1] = np.ravel([[np.mean(ys)]*2 for ys in grouper(yconn[1:-1], 2)]).tolist()

l = Line2D(np.repeat(xconn,2), yconn, transform=fig.transFigure, ls='--', lw=1, c='k')
fig.add_artist(l)
enter image description here

关于python - 在 matplotlib 中跨子图绘制分界线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65384260/

相关文章:

python - 使用 numpy 向量化 "pure"函数,假设有很多重复项

python - 与 Pandas 一起报道

python - 傅立叶空间中的滤波器表现不佳

python - 如何对 Pandas 数据框进行二分搜索以获取列值的组合?

python - 进程的异步生成 : design question - Celery or Twisted

python - 在matplotlib中从pandas系列制作线图时显示分类x轴值

python - 使用 bool 数组的 Numpy 索引

python - 根据索引分配值的最快方法

python - 如何使用 python 更快地读取文件中的几行?

python - Django +Celery +SQS -> boto.exception.SQSError : SQSError: 599 gnutls_handshake()