带有多个错误栏的ggplot position_dodge

时间:2016-03-13 09:57:43

标签: r ggplot2 facet-wrap

对于两个分类变量的每个交叉分类,我有五个数据点。我试图在误差条之间添加一些均匀的间距,以便它们在刻面的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")

enter image description here

我已经尝试过使用width参数,但无论值是什么,我都会得到相同的图。

2 个答案:

答案 0 :(得分:7)

我相信您需要将一个因子变量添加到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, ...

enter image description here

答案 1 :(得分:0)

我之前使用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")