条形 x-tick 与图像不一样

bar x-tick not as same as the image

我不确定我是否使用了错误的数据,或者是否有我需要编辑但没有看到的数据。如果有人可以看一下代码,那就太好了。这里的问题是第一个柱的 yerr 在 x=0 并且在图像中 yerr 大约在 2.5

有人知道我做错了什么或忘记编辑了吗?

最终结果应该是:

我的代码:

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)

y_raw = np.random.randn(1000).cumsum() + 15
x_raw = np.linspace(0, 24, y_raw.size)

x_pos = x_raw.reshape(-1, 100).min(axis=1)
y_avg = y_raw.reshape(-1, 100).mean(axis=1)
y_err = y_raw.reshape(-1, 100).ptp(axis=1)
bar_width = x_pos[1] - x_pos[0]

x_pred = np.linspace(0, 30)
y_max_pred = y_avg[0] + y_err[0] + 2.3 * x_pred
y_min_pred = y_avg[0] - y_err[0] + 1.2 * x_pred

barcolor, linecolor, fillcolor = 'wheat', 'salmon', 'lightblue'

fig, axes = fig, ax = plt.subplots()
axes.set_title(label="Future Projection of Attitudes", fontsize=15)
plt.xlabel('Minutes since class began', fontsize=12)
plt.ylabel('Snarkiness (snark units)', fontsize=12)
fig.set_size_inches(8, 6, forward=True)



axes.fill_between(x_pred, y_min_pred, y_max_pred ,color='lightblue')

axes.plot(x_raw, y_raw, color='salmon')

vert_bars = axes.bar(x_pos, y_avg, yerr=y_err, color='wheat', width = bar_width, edgecolor='grey',error_kw=dict(lw=1, capsize=5, capthick=1, ecolor='gray'))
axes.set(xlim=[0, 30], ylim=[0,100])

plt.show()

yerr 表示平均值与 min/max 之间的差异。现在您正在使用最大值和最小值之间的全部差异。您可以将其除以 2 以获得更好的近似值。要获得准确的值,您可以显式计算它们(参见代码示例)。

此外,默认情况下,条形图与其 x-position 居中对齐。您可以使用 align='edge' 到 left-align 它们(因为 x_pos 被计算为条形代表的范围的最小值)。您还可以在 err_kw 中设置 clip_on=False 以确保误差线永远不会被轴剪裁。

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(1)

y_raw = np.random.randn(1000).cumsum() + 15
x_raw = np.linspace(0, 24, y_raw.size)

x_pos = x_raw.reshape(-1, 100).min(axis=1)
y_avg = y_raw.reshape(-1, 100).mean(axis=1)
y_min = y_raw.reshape(-1, 100).min(axis=1)
y_max = y_raw.reshape(-1, 100).max(axis=1)
bar_width = x_pos[1] - x_pos[0]

x_pred = np.linspace(0, 30)
y_max_pred = y_avg[0] + y_err[0] + 2.3 * x_pred
y_min_pred = y_avg[0] - y_err[0] + 1.2 * x_pred

barcolor, linecolor, fillcolor = 'wheat', 'salmon', 'lightblue'

fig, ax = plt.subplots(figsize=(8, 6))
ax.set_title(label="Future Projection of Attitudes", fontsize=15)
ax.set_xlabel('Minutes since class began', fontsize=12)
ax.set_ylabel('Snarkiness (snark units)', fontsize=12)

ax.fill_between(x_pred, y_min_pred, y_max_pred, color='lightblue')

ax.plot(x_raw, y_raw, color='salmon')

vert_bars = ax.bar(x_pos, y_avg, yerr=(y_avg - y_min, y_max - y_avg),
                   color='wheat', width=bar_width, edgecolor='grey', align='edge',
                   error_kw=dict(lw=1, capsize=5, capthick=1, ecolor='grey', clip_on=False))
ax.set(xlim=[0, 30], ylim=[0, 100])
plt.tight_layout()
plt.show()