繁体   English   中英

带有多个错误栏的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")

在此输入图像描述

我已经尝试过使用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, ...

在此输入图像描述

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM