ggplot position_dodge 带有多个误差线

ggplot position_dodge with multiple error bars

对于两个分类变量的每个交叉分类,我有五个数据点。我试图在误差线之间添加一些均匀的间距,这样它们就不会在多面 ggplot2 图中重叠,但失败了。数据大概是这样的...

library(ggplot2)
library(dplyr)

df0 <- iris %>%
  group_by(Species) %>%
  mutate(long_sepal = ifelse(Sepal.Length > mean(Sepal.Length),
                             yes = "long", no = "short")) %>%
  group_by(Species, long_sepal) %>%
  mutate(petal_rank = order(Petal.Width)) %>%
  filter(petal_rank <= 5)

> df0
# Source: local data frame [30 x 7]
# Groups: Species, long_sepal [6]
# 
#    Sepal.Length Sepal.Width Petal.Length Petal.Width Species long_sepal petal_rank
#           (dbl)       (dbl)        (dbl)       (dbl)  (fctr)      (chr)      (int)
# 1           5.4         3.9          1.7         0.4  setosa       long          1
# 2           4.6         3.4          1.4         0.3  setosa      short          1
# 3           5.0         3.4          1.5         0.2  setosa      short          2
# 4           4.4         2.9          1.4         0.2  setosa      short          3
# 5           4.9         3.1          1.5         0.1  setosa      short          4
# 6           5.4         3.7          1.5         0.2  setosa       long          3
# 7           5.8         4.0          1.2         0.2  setosa       long          4
# 8           5.2         4.1          1.5         0.1  setosa       long          2
# 9           5.5         4.2          1.4         0.2  setosa       long          5
# 10          4.5         2.3          1.3         0.3  setosa      short          5
# ..          ...         ...          ...         ...     ...        ...        ...

到目前为止的情节代码。

ggplot(data = df0, 
       aes(x = long_sepal, y = Petal.Width, 
           ymin = Petal.Width-0.05, 
           ymax = Petal.Width+0.05)) + 
  geom_pointrange(position = position_dodge(width = 0.4)) +
  facet_wrap(~ Species, scales = "free")

我试过弄乱宽度参数,但无论值如何,我都得到了相同的图。

我以前用过position = position_jitter()来避免点重叠, 我认为这可能是您的解决方案。

尝试:

    ggplot(data = df0, 
       aes(x = long_sepal, y = Petal.Width, 
           ymin = Petal.Width-0.05, 
           ymax = Petal.Width+0.05)) + 
  geom_pointrange(position = position_jitter()) +
  facet_wrap(~ Species, scales = "free")

我认为您需要向 df0 添加一个因子变量,这样您就可以避开 long_sepal 内的观察结果。

# Create new grouping column by which we can dodge
df0$fac <- factor(unlist(sapply(as.vector(table(df0$long_sepal)), seq_len)))

# Assign fac to "group = " inside the aes()
... aes(x = long_sepal, y = Petal.Width, group = fac, ...