我已经使用df创建了一个填充的条形图(下面使用的代码)。我想在条形图中打印每个“竞赛”的比例。
Demo_17 <- tidyr::pivot_longer(Race_17, -c("State",), names_to = "Race", values_to = "num") %>%
ggplot(aes(x=State, y=num, fill = Race)) +
geom_bar(position="fill", stat="identity")
Demo_17 +
labs(x = "Population", y = "State", title = "US State Demographics 2017")
这是我使用的df:美国人口统计数据
我看过其他类似的问题,但是代码很长且很难遵循,特别是如果它与您自己的数据无关。
谁能引导我正确的方向?
尝试这个。在绘制之前只需计算份额即可。使用scales::percent
了漂亮的格式:
Demo_17 <- tidyr::pivot_longer(Race_17, -c("State",), names_to = "Race", values_to = "num") %>%
# compute pct share of race by state
group_by(State) %>%
mutate(pct = num / sum(num)) %>%
ggplot(aes(x=State, y=num, fill = Race)) +
geom_bar(position="fill", stat="identity") +
geom_text(aes(label = scales::percent(pct)), position = "fill")
Demo_17 + labs(x = "Population",
y = "State",
title = "US State Demographics 2017")
使用以下方法的示例mtcars
:
library(ggplot2)
library(dplyr)
mtcars %>%
count(cyl, gear, name = "num") %>%
group_by(cyl) %>%
mutate(pct = num / sum(num)) %>%
ggplot(aes(x=cyl, y=num, fill = gear)) +
geom_bar(position="fill", stat="identity") +
geom_text(aes(label = scales::percent(pct)), position = "fill", vjust = 1.5, color = "white")
由reprex软件包(v0.3.0)创建于2020-04-20
另外:如果您只想显示超过10%的股票的标签(仅举一个例子,请根据需要进行调整),则可以ifelse()
在label
参数内添加一个geom_text
:
mtcars %>%
count(cyl, gear, name = "num") %>%
group_by(cyl) %>%
mutate(pct = num / sum(num)) %>%
ggplot(aes(x=cyl, y=num, fill = gear)) +
geom_bar(position="fill", stat="identity") +
geom_text(aes(label = ifelse(pct>0.10, scales::percent(pct), "")), position = "fill", vjust = 1.5, color = "white")
您会注意到9%的标签不再显示。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句