向条形图添加比例

Adding proportions to a bar chart

我用我的 df 创建了一个填充条形图(下面使用的代码)。我想在条形图中打印每个 "race" 的比例。

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

我看过其他类似的问题,但代码又长又难理解,尤其是当它与您自己的数据无关时。

谁能指引我正确的方向?

为您的图表添加标签的是 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 以便人们可以有效地帮助您。

试试这个。在绘图之前简单地计算份额。使用 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 年 4 月 20 日创建

另外: 如果您希望只显示超过 10% 的股份的标签(仅举个例子,按需要调整),那么您可以在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% 标签不再显示。