加载所需要的包
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
普通条形图
ggplot(data, aes(fill=Legend, y=Count, x=Year)) + geom_bar(position="dodge", stat="identity")
这个图是按照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")
改变顺序为A,X,E