首页 > 解决方案 > 使用 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] 有没有办法改变它?

[1]: https://i.stack.imgur.com/sZDXc.png##标题##

标签: rggplot2

解决方案


如果我们想以相同的出现顺序对其进行重新排序,请使用factorwithlevels指定作为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')

推荐阅读