【发布时间】:2020-06-11 11:49:08
【问题描述】:
我已经制定了一个情节,但我有两个问题需要帮助。
问题 1)
如何在条形的每个部分中居中标签? 在寻找解决方案时,我试图改变这一行:
geom_text(aes(label= paste(round(pct),"%")), color = "white", size=2.6, position="fill", stat="identity")
到
geom_text(aes(label= paste(round(pct),"%")), color = "white", size=2.6, position=position_stack(vjust = 0.5))
这会将标签放在正确的位置,但现在彩色条不打印了。
问题 2)
有没有办法自动处理重叠标签?另一个有用的解决方案可能是偏移所有其他标签,以便第一个标签在条的中间上方,第二个标签在中间下方(我希望这是有道理的)。也欢迎其他解决方案。
重现我的情节的代码:
library(ggplot2)
exdata <- structure(list(Var1 = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L,
4L), .Label = c("Meget ofte", "Ofte", "Nogle gange", "Aldrig eller næsten aldrig"
), class = "factor"), Freq = c(4L, 16L, 50L, 38L, 6L, 5L, 55L,
43L), spm = c("Question 1: aaaaaabbbbbbbbbcccccc", "Question 1: aaaaaabbbbbbbbbcccccc",
"Question 1: aaaaaabbbbbbbbbcccccc", "Question 1: aaaaaabbbbbbbbbcccccc",
"Question 2: aaaaaabbbbbbbbbcccccc", "Question 2: aaaaaabbbbbbbbbcccccc",
"Question 2: aaaaaabbbbbbbbbcccccc", "Question 2: aaaaaabbbbbbbbbcccccc"
), pct = c(3.7037037037037, 14.8148148148148, 46.2962962962963,
35.1851851851852, 5.5045871559633, 4.58715596330275, 50.4587155963303,
39.4495412844037)), row.names = 21:28, class = "data.frame")
palette1 <- c("#00ABA4", "#008983", "#006763", "#004543")
plot1 <- ggplot(data=exdata, aes(y=Freq, x=spm, fill= fct_rev(Var1))) +
geom_bar(position="fill", stat="identity") +
scale_fill_manual(values=c(palette1)) +
geom_text(aes(label= paste(round(pct),"%")), color = "white", size=2.6, position="fill", stat="identity") +
coord_flip() +
labs(fill = "Svar") +
labs(title = "Hvor often do you do these things?") +
ylab("Percentage") +
xlab("Question") +
theme(legend.position="bottom", legend.title=element_text(size=10)) +
guides(fill =guide_legend(reverse = TRUE,nrow=2,byrow=TRUE))
plot1
【问题讨论】:
标签: r ggplot2 bar-chart stacked-chart