【问题标题】:ValueError: The lengths of the data (3) and the error 5 do not matchValueError:数据(3)的长度和错误5不匹配
【发布时间】:2022-01-18 03:15:29
【问题描述】:

我正在使用下面这个简单的代码在 seaborn 中绘制数据:

df = pd.DataFrame([['A','car',10,1],
                   ['A','plane',15,1],
                   ['A','bike',25,3],
                   ['B','plane',20,2],
                   ['C','bike',30,3]], 
                  columns = ['x','type','y', 'y_err']) 


print(df)


fig, axes = plt.subplots(figsize=(5, 5))

sns.set_theme(style="darkgrid")
 
g = sns.barplot(
      ax = axes, data=df,
      x="x", y='y', hue="type",
      palette="dark", alpha=.6 
)

这是输出

当我尝试插入自定义错误栏时遇到问题,在 sns.barplot 函数中添加 yerr=df['y_err']。 问题是:

ValueError: The lengths of the data (3) and the error 5 do not match

我使用 seaborn 是因为我需要根据上面示例中的特定 x 绘制不同数量的条形图。

【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案1】:

    如果您根据需要pivot 您的数据,您可以在没有seaborn 的情况下执行此操作:

    data = df.pivot("x", "type", "y")
    errors = df.pivot("x", "type", "y_err")
    
    data.plot.bar(yerr=errors)
    
    输出:

    【讨论】:

    • 有没有办法让酒吧居中?例如,第二个刻度上的绿色条和第三个刻度上的蓝色条是分散的
    • 它们是第一个完整组或列名。蓝色(自行车)是每组中最左边的。每个组不能有不同的中心。
    • 那么有没有办法把它们集中起来呢?即使用其他方法也不行?
    • @Alessandro - 不是说没有。但如果我知道一个,我会编辑我的答案。
    猜你喜欢
    • 2022-01-13
    • 2016-08-31
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 2022-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多