ggplot2 position_dodge会影响错误栏宽度

我试图用错误栏创建一个直线和点图.它有不同的因素,但有些因素只有一个值.我发现如果我使用position_dodge,其中一个单值因子与图中的其他误差条相比具有更宽的误差条.不知何故,position_dodge对错误栏的宽度有影响.我之前没有找到任何有同样问题的人,所以我希望有人可以帮助我.

虚拟数据:

require(ggplot2)

x <- c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,3,3,5)
y <- c(3,5,6,3,5,3,5,6,2,6,3,7,3,6,2,1,5,8,7)
se <- x*0.2
treatment <- c("A", "B","C", "D","A", "B","C", "D","A", "B","C", "D","A",    "B","C", "D","E", "F", "G" )
data <- data.frame(x, y, se ,treatment)
data$treatment <- as.factor(data$treatment)

首先是没有position_dodge的情节 – 一切都很好

# Without position dodge
myplot <- ggplot(data, aes(x=x, y=y, group= treatment,  fill = treatment, colour = treatment)) +
  geom_line(stat="identity", size = 1) +
  geom_point(stat="identity", size = 3, shape = 21) + 
  geom_errorbar(aes(ymin = y-se, ymax = y+se), width = 0.2)

myplot

plot without position_dodge

现在是一个位置躲闪的情节:

# With position dodge
myplot <- ggplot(data, aes(x=x, y=y, group= treatment,  fill = treatment, colour = treatment)) +
  geom_line(stat="identity", size = 1, position=position_dodge(width=0.2)) +
  geom_point(stat="identity", size = 3, shape = 21, position=position_dodge(width=0.2)) + 
  geom_errorbar(aes(ymin = y-se, ymax = y+se), width = 0.2, position=position_dodge(width=0.2))

myplot

Plot with position_dodge

如您所见,最右侧的误差条与其他误差条相比具有更大的宽度.这可能是因为此点没有重叠的x变量,并且误差条可以具有正常大小.我仍然想知道如何让错误条具有相同的宽度.

正如@aosmith建议的那样,对此的修复是将误差条的宽度缩放到具有该x的点数.但是,这不需要手动完成.下面我使用dplyr根据x的点数在data.frame中创建一个新列.我也删除了组和填充映射,因为这里都不需要(假设形状改变为用颜色而不是填充颜色填充的圆形版本).最后,为了避免重复,我已经定义了一次位置,然后为每个geom使用了一个变量.

library(dplyr)
data <- data %>%
  group_by(x) %>%
  mutate(
    width = 0.1 * n()
  )

pos <- position_dodge(width = 0.2)
myplot <-
  ggplot(data,
         aes(
           x = x,
           y = y,
           colour = treatment,
           width = width
         )) +
  geom_line(size = 1, position = pos) +
  geom_point(size = 3, shape = 16, position = pos) +
  geom_errorbar(aes(ymin = y - se, ymax = y + se), position = pos)

myplot

Final image

https://stackoverflow.com/questions/42716425/ggplot2-position-dodge-affects-error-bar-width

转载注明原文:ggplot2 position_dodge会影响错误栏宽度