如何创建带有长水平误差线的条形图?

问题描述 投票:-1回答:1

“示例剧情”

我想模仿给定图像中的浅蓝色背景线。有人可以告诉我如何使用Matplotlib吗?

基本上,它是this的简单版本。

python matplotlib seaborn
1个回答
0
投票

这里是使用拉伸的一维图像绘制带的方法。图像会达到填充整个宽度和所需高度的程度。将颜色映射的vmax设置得更高一些,以避免过浅的颜色,这种颜色与白色背景太相似。

import matplotlib.pyplot as plt
import numpy as np

# create some test data
N = 40
x = np.linspace(-3, 3, N)
values = np.random.normal(0, 2, N)

error_bands = np.array([2, 1, 0, 0, 1, 2])
plt.imshow(error_bands.reshape(-1, 1), extent=[-10, 10, -3, 3], origin='lower',
           cmap='Blues_r', vmin=error_bands.min(), vmax=error_bands.max() * 1.4, alpha=0.3)

plt.axhline(0, color='blueviolet', lw=3) # horizontal line at x=0

plt.bar(x, values, width=(x[1] - x[0]) * 0.8, bottom=0, color='blueviolet')

plt.gca().set_aspect('auto')  # removed the fixed aspect ratio forced by imshow
plt.xlim(x[0] - 0.3, x[-1] + 0.3) # explicitly set the xlims, shorter than the extent of imshow

plt.show()

resulting plot

PS:一种更简单的方法,用一些调用imshow的方式将axhspan替换为彼此之间的绘制水平条,并使用一个较小的alpha:

for i in range(1, 4):
    plt.axhspan(-i, i, color='b', alpha=0.1)

alternative plot

© www.soinside.com 2019 - 2024. All rights reserved.