gpt4 book ai didi

r - ggplot position_dodge 带有多个误差线

转载 作者:行者123 更新时间:2023-12-04 11:18:20 25 4
gpt4 key购买 nike

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

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

最佳答案

我认为您需要向 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

关于r - ggplot position_dodge 带有多个误差线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35968875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com