r - 使用 R ggplot 控制条形图中的条形顺序
问题描述
使用 R,我希望条形图中的条形按特定顺序排列。
顺序是:
a<-c("no exercise", "strength", "moderate aerobics", "moderate aerobics + strength", "high aerobics")
然后是价值观,让我们说:
b<- c(10, 20, 25, 40, 40)
df<-data.frame(a, b)
创建条形图时,条形图的顺序是字母顺序,而不是原始顺序:
ggplot(df) +
geom_bar( aes(x=a, y=b), stat="identity", fill="red")
[在此处输入图像描述][1] 有没有办法改变它?
解决方案
如果我们想以相同的出现顺序对其进行重新排序,请使用factor
withlevels
指定作为unique
列的值(这里,我们只有unique
值,但我们将unique
其用作一般情况,unique
将按其出现的顺序获取唯一值)
library(dplyr)
library(ggplot2)
df %>%
mutate(a = factor(a, levels = unique(a))) %>%
ggplot() +
geom_bar(aes(x = a, y = b), stat = 'identity', fill = 'red')
推荐阅读
- mariadb - 从导出的 sql 文件中查找数据库的默认排序规则
- mysql - 表被“spring.jpa.hibernate.ddl-auto”截断以验证
- google-cloud-firestore - 如何获取要在 Firebase 云功能中使用的 Firebase 项目区域值
- tensorflow2.0 - “这个工人或司机正在等待接收一个类定义,所以......”
- python - 将空字符列添加到熊猫数据框很奇怪
- r - 为什么 ifelse 函数会产生 NA
- angular - Angular 材质 - 应用不同的样式
- couchbase - 简单 N1QL 查询的查询错误,错误代码 4010,
- docker - 詹金斯的示例管道显然无法正常工作
- python - 我们可以使用 selenium 网络浏览器在网站上使用搜索功能吗