簡體   English   中英

在R ggplot2中位置=“填充”的條形圖上繪制標簽

[英]Plotting labels on bar plots with position = “fill” in R ggplot2

如何使用ggplot2繪制帶有計數標簽的“填充”條形圖?

我可以對“堆疊”的酒吧進行此操作。 但是我非常困惑。

這是使用dplyrmpg數據集的可復制示例

library(ggplot)
library(dplyr)

mpg_summ <- mpg %>%
  group_by(class, drv) %>%
  summarise(freq = n()) %>%
  ungroup() %>%
  mutate(total = sum(freq), 
         prop = freq/total)

g <- ggplot(mpg_summ, aes(x = class, y = prop, group = drv))
g + geom_col(aes(fill = drv)) +
  geom_text(aes(label = freq), position = position_stack(vjust = .5))

在此處輸入圖片說明

但是,如果我嘗試繪制實心條的計數,則不起作用

g <- ggplot(mpg_summ, aes(x=class, fill=drv))
g + stat_count(aes(y = (..count..)/sum(..count..)), geom="bar", position="fill")  +
  scale_y_continuous(labels = percent_format())

在此處輸入圖片說明

此外,如果我嘗試:

g <- ggplot(mpg_summ, aes(x=class, fill=drv))
g + geom_bar(aes(y = freq), position="fill")  +
  geom_text(aes(label = freq), position = "fill") +
  scale_y_continuous(labels = percent_format())

我得到:

Error: stat_count() must not be used with a y aesthetic.

我錯過了最后一個問題的填充部分。 這應該使您到達那里:

library(ggplot2)
library(dplyr)

mpg_summ <- mpg %>%
  group_by(class, drv) %>%
  summarise(freq = n()) %>%
  ungroup() %>%
  mutate(total = sum(freq), 
         prop = freq/total)

g <- ggplot(mpg_summ, aes(x = class, y = prop, group = drv))
g + geom_col(aes(fill = drv), position = 'fill') +
  geom_text(aes(label = freq), position = position_fill(vjust = .5))

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM