如何避免在matplotlib中出现重叠的误差线?

10
我希望能够创建两个不同数据集的图表,类似于这个答案中呈现的。

enter image description here

在上面的图像中,作者通过向新数据集添加一些小的随机分散物来解决误差条重叠问题。
在我的问题中,我必须绘制类似的图形,但x轴上有一些分类数据:

enter image description here

您有没有关于如何使用分类变量在x轴上轻微移动第二个数据集的误差条的想法?我希望避免柱状图之间的重叠,以便更容易地进行可视化。

3个回答

11
考虑以下突出绘图的方法——结合使用errorbarfill_between,并设置非零透明度:
import random
import matplotlib.pyplot as plt

# create sample data
N = 8
data_1 = {
    'x': list(range(N)),
    'y': [10. + random.random() for dummy in range(N)],
    'yerr': [.25 + random.random() for dummy in range(N)]}
data_2 = {
    'x': list(range(N)),
    'y': [10.25 + .5 * random.random() for dummy in range(N)],
    'yerr': [.5 * random.random() for dummy in range(N)]}

# plot
plt.figure()
# only errorbar
plt.subplot(211)
for data in [data_1, data_2]:
    plt.errorbar(**data, fmt='o')
# errorbar + fill_between
plt.subplot(212)
for data in [data_1, data_2]:
    plt.errorbar(**data, alpha=.75, fmt=':', capsize=3, capthick=1)
    data = {
        'x': data['x'],
        'y1': [y - e for y, e in zip(data['y'], data['yerr'])],
        'y2': [y + e for y, e in zip(data['y'], data['yerr'])]}
    plt.fill_between(**data, alpha=.25)

结果:

在此输入图像描述


谢谢您的建议。然而,这个想法并不适合我的问题。所有的变量都是分类变量,我不能让它们之间有连线。 - revy
@revy 无论是分类还是数值都没关系,它们只是标签。将整数替换为您选择的任何对象,您将得到与X或Y轴旁边不同标签的完全相同的图形。例如,用N个单词- alegriadesgosto等替换list(range(N))。那很容易。 - user10325516
太棒了!我喜欢用字典的方式定义数据。从现在开始,我也会一直这样做! - quoniam

11

您可以通过将默认数据转换添加到数据空间中的先前翻译来翻译每个误差条。当知道类别通常相距一个数据单位时,这是可能的。

import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt
from matplotlib.transforms import Affine2D

x = list("ABCDEF")
y1, y2 = np.random.randn(2, len(x))
yerr1, yerr2 = np.random.rand(2, len(x))*4+0.3

fig, ax = plt.subplots()

trans1 = Affine2D().translate(-0.1, 0.0) + ax.transData
trans2 = Affine2D().translate(+0.1, 0.0) + ax.transData
er1 = ax.errorbar(x, y1, yerr=yerr1, marker="o", linestyle="none", transform=trans1)
er2 = ax.errorbar(x, y2, yerr=yerr2, marker="o", linestyle="none", transform=trans2)

plt.show()

enter image description here

或者,您可以在应用数据变换后翻译误差条,从而将它们移动到点的单位。

import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt
from matplotlib.transforms import ScaledTranslation

x = list("ABCDEF")
y1, y2 = np.random.randn(2, len(x))
yerr1, yerr2 = np.random.rand(2, len(x))*4+0.3

fig, ax = plt.subplots()

trans1 = ax.transData + ScaledTranslation(-5/72, 0, fig.dpi_scale_trans)
trans2 = ax.transData + ScaledTranslation(+5/72, 0, fig.dpi_scale_trans)
er1 = ax.errorbar(x, y1, yerr=yerr1, marker="o", linestyle="none", transform=trans1)
er2 = ax.errorbar(x, y2, yerr=yerr2, marker="o", linestyle="none", transform=trans2)

plt.show()

enter image description here

虽然两种情况下的结果看起来相似,但它们在根本上是不同的。当交互式缩放轴或更改图形大小时,您将观察到这种差异。


0

目前你的回答不够清晰,请编辑并添加更多细节,以帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接