首页 > 解决方案 > Matplotlib 在不同形状图之间填充

问题描述

我想在我的两个地块之间填充颜色空间(地块是使用 制作的plt.plot())。问题是,这个图的数据由不同数量的记录组成,所以当我尝试这样做时,plt.fill_between()我收到一个错误ValueError: operands could not be broadcast together with shapes (36,) (21,)

我的数据在数据框中。使用以下代码,我可以部分完成我想要的:

plt.fill(
    np.append(data1['x_values'], data2['x_values'][::-1]),
    np.append(data1['y_values'], data2['y_values'][::-1]),
    color="tab:gray",
)

但我还需要使用where仅在plt.fill_between(). 我该如何完成它?

编辑

情节线相互交叉,所以最终我希望能够做类似的事情:where data1['y_values'] > data2['y_values]

标签: pythonmatplotlibplot

解决方案


也许这就是你要找的:

x_all = np.append(data1['x'], data2['x'][::-1])
y_all = np.append(data1['y'], data2['y'][::-1])

# set condition
y_idxs = np.where(y_all < 5)[0] 

# assign the right values to your new vectors
new_x, new_y = [x_all[idx] for idx in y_idxs], [y_all[idx] for idx in y_idxs]

plt.fill_between(new_x, new_y)

编辑:

随着你的新状况data1['y_values'] > data2['y_values']

y_idxs = [i for i,x in enumerate(data1['y_values'] if len(data1['y_values']) < len(data2['y_values']) else data2['y_values']) if data1['y_values'][i] > data2['y_values'][i]]
new_x, new_y = [x_all[idx] for idx in y_idxs], [y_all[idx] for idx in y_idxs]
plt.fill_between(new_x, new_y)

推荐阅读