首页 > 解决方案 > 如何将普通条形图转换为百分比条形图

问题描述

请帮助我使用 ggplot2 将其转换为百分比条形图。我尝试了几种方法,但百分比值不正确。我还想将百分比的数值放在每个条形图的顶部。

g<-read.csv("survey.csv")
data<-g

data$Number.of.Beetle <- trimws(data$Number.of.Beetle)
lvls <- unique(data$Number.of.Beetle)
lvls <- stringr::str_sort(lvls, numeric = TRUE)
data$Number.of.Beetle <- factor(data$Number.of.Beetle, levels = lvls)

 lvls2 <- unique(data$Building.Age)
lvls2 <- lvls2[c(2, 3, 1)]
data$Building.Age <- factor(data$Building.Age, levels = lvls2)

 ggplot(data, aes(x = Locality.Division))+
   geom_bar(aes(fill = Number.of.Beetle), position = "dodge")+
   facet_wrap(~ Building.Age) +
   labs(title = "Comparison between Number of beetle, Locality division and Age of the building",subtitle ="Building age") 

在此处输入图像描述 reprex 包于 2021-06-28 创建 (v2.0.0 )

标签: rggplot2

解决方案


aes您可以在中创建一个比例geom_bar

library(scales)

ggplot(data, aes(x = Locality.Division))+
  geom_bar(aes(y = (..count..)/sum(..count..), fill = Number.of.Beetle), position = "dodge")+
  scale_y_continuous(labels=scales::percent) +
  ylab("relative frequencies") +
  facet_wrap(~ Building.Age) +
  labs(title = "Comparison between Number of beetle, Locality division and Age of the building",subtitle ="Building age") 

推荐阅读