R语言ggplot画条形图按照想要的顺序排列

加载所需要的包

library(ggplot2)
library(dplyr)

创建数据集

Year <- c(rep("2012" , 3) , rep("2013" , 3) , rep("2014" , 3) , rep("2015" , 3) )
Legend <- rep(c("A" , "X" , "E") , 4)
Count <- abs(rnorm(12 , 0 , 15))
data <- data.frame(Year,Legend,Count)
data

《R语言ggplot画条形图按照想要的顺序排列》

普通条形图

ggplot(data, aes(fill=Legend, y=Count, x=Year)) + geom_bar(position="dodge", stat="identity")

《R语言ggplot画条形图按照想要的顺序排列》
这个图是按照A,E,X字母表的顺序排序的。想改变这个顺序

指定顺序的条形图

data %>%
  mutate(Legend = factor(Legend, levels = c("A", "X", "E"))) %>%
  ggplot(aes(fill = Legend, y = Count, x = Year)) +
  geom_bar(position = "dodge", stat = "identity")

《R语言ggplot画条形图按照想要的顺序排列》
改变顺序为A,X,E

    原文作者:sixk
    原文地址: https://blog.csdn.net/weixin_48172266/article/details/117537465
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞