ggplot 在 geom 条形图中的计数旁边的括号中显示份额

ggplot show shares in brackets next to counts in geom bar plots

假设我有一个包含类别、计数和份额的简单数据框,我想使用 ggplot

对其进行绘制
cat1 <- c("category1",
          "category2",
          "category3",
          "category4",
          "category5")
count <- c(12, 43, 31, 25, 11)

df <- data.frame(cat1, count)
df$share <- df$count / sum(df$count) * 100

require(ggplot2)

ggplot(df, aes(cat1, count)) +
  geom_bar(stat = "identity") +
  geom_text(aes(label = round(count, 2)), vjust = "bottom", size = 5)

有没有办法在每个条形图的顶部将计数旁边的括号中的份额显示为标签,就像下面的屏幕截图(摘自 this blog)中所做的那样?

一个选项是使用 paste0 将一列标签添加到您的数据框。为了达到你想要的结果,你可以使用 paste0(round(df$count, 2), " (", round(df$share, 1), "%)"):

cat1 <- c("category1",
          "category2",
          "category3",
          "category4",
          "category5")
count <- c(12, 43, 31, 25, 11)

df <- data.frame(cat1, count)
df$share <- df$count / sum(df$count) * 100
df$label <- paste0(round(df$count, 2), " (", round(df$share, 1), "%)")
require(ggplot2)
#> Lade nötiges Paket: ggplot2

ggplot(df, aes(cat1, count)) +
  geom_bar(stat = "identity") +
  geom_text(aes(label = label), vjust = "bottom", size = 5)

reprex package (v0.3.0)

于 2020-03-25 创建

您可以手动添加文本

ggplot(df, aes(cat1, count)) +
  geom_bar(stat = "identity") +
  annotate("text", x = 1, y = 14, label = "[square]",hjust=0.5, vjust=0, 
           cex=5, fontface=2, col="black")