r - 如何将普通条形图转换为百分比条形图
问题描述
请帮助我使用 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 )
解决方案
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")
推荐阅读
- android - Flutter Flat Button Color Property Not Working
- c++ - 如何使用 CMake 在 android 构建上编译和共享两个 c++ 库
- javascript - 开始时标签是否可能导致css和js无法加载
- amazon-cloudformation - 在 AWS 实例创建之间添加延迟
- javascript - 使用子值消除父节点
- javascript - 向下滚动时导航栏更改,如何使更改响应?
- java - 使用 Java 从共享点检索数据并对其进行处理的最佳方法是什么?
- java - 有效地从服务器套接字读取传入数据的方法
- rust - 如何实例化近协议向量?
- css - 居中CSS网格容器