ggplot中geom_histogram()报错! `data` must be uniquely named but has duplicate columns

Error in geom_histogram():
! Problem while computing aesthetics.
ℹ Error occurred in the 1st layer.
Caused by error in FUN():
! data must be uniquely named but has duplicate columns
Run rlang::last_error() to see where the error occurred.

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 以下回答来自chatgpt:

    根据参考资料中提供的信息和我现有的知识,这个问题是由于使用了重复列名的数据集所引起的。解决方法是重新命名数据集的列名,确保所有列名唯一。如果数据集比较大,可以尝试使用dplyr包中的 rename() 函数来进行列名的批量重命名。 代码示例如下:

    # 从ggplot绘图代码中提取数据集
    surge <- c(0.81,2.21,1.23,0.59,1.09,0.72,0.83,1.38,0.25,0.69,0.7,0.72,1.39,1.75,1.01,0.81,0.96,0.75,0.62,1.99,1.27,0.83,3.19,1.49,0.99)
    surgeLing <- data.frame(x=surge)
    
    # 重命名列名
    library(dplyr)
    surgeLing <- surgeLing %>% rename(x_value = x)
    
    # 使用重命名后的数据集进行绘图
    ggplot(surgeLing, aes(x = x_value)) +
      geom_histogram(binwidth = 1) +
      geom_text(stat = "bin", aes(label = round(..count../length(surge),2)),
                vjust = -0.5, binwidth = 1)
    

    需要注意的是在绘制ggplot前,需要重命名数据集的列名,并使用重命名后的数据集进行绘图。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^

说明你的数据的data里面有重复的列,检查一下。