我希望標簽出現在正負條之外,所以我不能簡單地使用 hjust 來移動位置。現在我有這個,它很接近......
score <- c(1, 2, 3, 4, 5, "X")
group1 <- c(0,0,5,-0.2,-4.9,0)
group2 <- c(0.1,0,-1.2,0.4,0.6,0.1)
group3 <- c(0.1,0,3.4,2.9,-6.4,0)
group4 <-c(0,0,-0.9,-0.3,1.3,0)
data <- data.frame(score=as.factor(score), Group1=group1, Group2=group2, Group3=group3, Group4=group4)
data_long <- pivot_longer(data, c(Group1, Group2, Group3, Group4))
data_long$label <- paste(round(data_long$value,1),"%",sep="")
data_long$value <- data_long$value/100
sig <- rep(0, 24)
sig[c(3, 9, 11, 15, 17, 19)] <- 1
sig <- as.factor(sig)
data_long <- cbind(data_long, sig)
bars <- data_long %>% filter(score != 2,
score != "X") %>%
ggplot(aes(x = value, y=name, fill=sig))
geom_bar(stat="identity")
scale_fill_manual(values=c("grey", "firebrick"))
scale_x_continuous(limits = ~ c(-1, 1) * max(abs(.x)),
labels = scales::percent)
facet_wrap(~score, scales = "free_x")
theme(legend.position = "none")
geom_text(aes(label=label,
x = value (0.005 * sign(value))), size = 3)
labs(x = "Deviation From Expected Value",
y = "Group",
title = "Deviations From Expected Value by Score",
caption = "Red bars statistically significant")
print(bars)
這將產生以下圖表

但請注意,在左上角,比例非常小,標簽與非零條相距甚遠。我假設這是因為我在 geom_text x 美學中使用的乘法因子對于該比例來說很大。我在那里嘗試了某種功能,考慮到了限制,但我得到了一個錯誤
Aesthetics must be valid data columns. Problematic aesthetic(s): x = ~(value (0.005 * max(abs(.x)) * sign(value)))
任何有關如何進行的建議將不勝感激。
uj5u.com熱心網友回復:
您可以hjust用作美學映射。如果您將其設定0.5 - sign(value)/2為 0,則正條為 0,負條為 1,根據需要。
data_long %>% filter(score != 2,
score != "X") %>%
ggplot(aes(x = value, y=name, fill=sig))
geom_bar(stat="identity")
scale_fill_manual(values=c("grey", "firebrick"))
scale_x_continuous(limits = ~ c(-1, 1) * max(abs(.x)),
labels = scales::percent)
facet_wrap(~score, scales = "free_x")
theme(legend.position = "none")
geom_text(aes(label=label,
x = value, hjust = 0.5 - sign(value)/2), size = 3)
labs(x = "Deviation From Expected Value",
y = "Group",
title = "Deviations From Expected Value by Score",
caption = "Red bars statistically significant")

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/435049.html
上一篇:有沒有辦法使用ggplot在R中創建直方圖,以便只顯示突出的箱的垂直線?
下一篇:ggplot:修改直方圖
