首页 > 解决方案 > R ggplot2 - 错误栏宽度问题

问题描述

我一直在尝试使用 ggplot2 绘制以下数据,但我遇到了错误栏的问题:

data1<-c(0.04, 0.5, 1.0, 1.5 ,2.0, 2.6, 3.1, 3.6,  0.9,0.56,0.4,0.33,0.27,0.2,0.15,0.1, 0.12, 0.17, 0.22 ,0.33, 0.45,  0.57, 0.74, 0.85)

sym<-as.data.frame(matrix(data = data1, ncol = 3, byrow = FALSE))

ggplot(data=sym, mapping = aes(x=sym[,1], y=sym[,2]))+
  theme(plot.background = element_rect(fill = "white"), 
        panel.background = element_rect(fill = "white", color="black",linetype = 1),
        panel.grid = element_blank(),
        plot.title = element_text(hjust = 0.5, size =30),
        axis.title = element_blank(),
        axis.ticks = element_line(color="black"),
        axis.ticks.length=unit(-0.25, "cm"),
        axis.text.x = element_text(margin=unit(c(0.5,0.5,0.5,0.5), "cm")), 
        axis.text.y = element_text(size=25, margin=unit(c(0.5,0.5,0.5,0.5), "cm")))+
  ggtitle("variable, symmetric error")+
  ylim(-1.0, 1.5)+
  xlim(0.0,4.5)+
  geom_line(color="blue",size=1.2)+
  geom_point(color="blue", size=4)+
  geom_errorbar(aes(ymin = sym[,2]-sym[,3], ymax = sym[,2]+sym[,3], x= sym[,1]),
                width=0.1, color="blue", size =1.2)

结果(主要)如预期的那样,但我无法弄清楚为什么第一个错误栏没有响应“宽度”设置。绘图显示第一个错误栏的问题,它没有响应设置的宽度参数

我的第一个猜测是,更改边距可能会导致某种重叠,这导致 R 在第一个点上没有按宽度绘制。但是,在 x 轴上向内移动数据没有任何区别。因此,我假设我一定错过了其他东西?

非常感谢任何输入!

标签: rggplot2graphicswidtherrorbar

解决方案


指出@stefan 和@RuiBarradas 关于变量名称和限制的好建议,您还可以尝试scale_x_continuous()scale_y_continuous()限制,因为它在下一个代码中使用:

ggplot(data=sym, mapping = aes(x=V1, y=V2))+
  theme(plot.background = element_rect(fill = "white"), 
        panel.background = element_rect(fill = "white", color="black",linetype = 1),
        panel.grid = element_blank(),
        plot.title = element_text(hjust = 0.5, size =30),
        axis.title = element_blank(),
        axis.ticks = element_line(color="black"),
        axis.ticks.length=unit(-0.25, "cm"),
        axis.text.x = element_text(margin=unit(c(0.5,0.5,0.5,0.5), "cm")), 
        axis.text.y = element_text(size=25, margin=unit(c(0.5,0.5,0.5,0.5), "cm")))+
  ggtitle("variable, symmetric error")+
  scale_y_continuous(limits = c(NA,1.5))+
  scale_x_continuous(limits = c(NA,4.5))+
  geom_line(color="blue",size=1.2)+
  geom_point(color="blue", size=4)+
  geom_errorbar(aes(ymin = V2-V3, ymax = V2+V3, x= V1),
                width=0.1, color="blue", size =1.2)

在此处输入图像描述


推荐阅读