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


r - ggplot position_dodge具有多个误差线-LMLPHP

我试图弄乱width参数,但是无论值如何,我都会得到相同的图。

最佳答案

我相信您需要在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, ...


r - ggplot position_dodge具有多个误差线-LMLPHP

08-07 03:37