gpt4 book ai didi

R ggplot : How to align points with dodged bars?

转载 作者:行者123 更新时间:2023-12-02 20:23:32 25 4
gpt4 key购买 nike

我想知道如何将 geom_point 点与 geom_bar 躲避条位置对齐。

根据年份参数对条形进行躲避,但无论年份参数如何,点都绘制在躲避条形的中间。

enter image description here

可重现的代码:

set.seed(42)
dat <- data.frame(Response = rep(paste0("Response",1:4),2),
Proportion = round(runif(8),2),
Year = c(rep(2017,4),rep(2018,4)))
industries <- data.frame(Response = rep(paste0("Response",1:4),6),
Proportion = round(runif(24),2),
Year = rep(c(rep(2017,4),rep(2018,4)),3),
Cat = rep(paste0("Cat",1:3),c(rep(8,3))))
ggplot(dat, aes(Response, Proportion, label = paste0(Proportion*100,"%"), fill = factor(Year))) +
geom_bar(stat = "identity", position = "dodge" ) +
geom_point(data = industries, aes(Response, Proportion, fill = factor(Year), col= Cat), size = 3) +
theme(axis.text.x = element_text(angle = 90)) +
scale_y_continuous(labels = scales::percent) +
geom_text(position = position_dodge(width = 1), angle = 90)

最佳答案

您需要在 aes() 中使用 group = Factor(Year),然后使用 position =position_dodge(1) (按照建议@Tung)。另外,在 aes() 中为 geom_point() 重复 x, y 是多余的:

ggplot(dat, aes(Response, Proportion, label = paste0(Proportion*100,"%"), 
fill = factor(Year))) +
geom_bar(stat = "identity", position = "dodge" ) +
geom_point(data = industries, aes(col= Cat, group = factor(Year)), size = 3,
position = position_dodge(1)) +
theme(axis.text.x = element_text(angle = 90)) +
scale_y_continuous(labels = scales::percent) +
geom_text(position = position_dodge(width = 1), angle = 90)

enter image description here

关于R ggplot : How to align points with dodged bars?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50650423/

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