在条形图中添加比例

问题描述 投票:0回答:2

我已经使用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:US Demographic Data

我看过其他类似的问题,但是代码很长而且很难遵循,特别是如果它与您自己的数据无关时。

有人可以引导我朝正确的方向吗?

r ggplot2 geom-bar geom-text
2个回答
0
投票

将标签添加到图表中的是geom_text()。也许像这样:

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") +
  geom_text(aes(y=num, x=State, labels=num), vjust=0.5)

无法测试它是否可以像这样很好地工作,或者是否需要进行一些修改,因为您只提供了数据集的屏幕快照,而不是可复制的示例。让我知道它是否有效,但是否需要更多关注,请阅读here,以便人们可以有效地帮助您。


0
投票

尝试一下。在绘制之前只需计算份额即可。使用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 package(v0.3.0)在2020-04-20创建

© www.soinside.com 2019 - 2024. All rights reserved.