如何阻止R按字母顺序排列?[duplicate]

ar7v8xwq  于 2023-01-18  发布在  其他
关注(0)|答案(1)|浏览(121)
    • 此问题在此处已有答案**:

How can I order the months chronologically in ggplot2 short of writing the months out?(1个答案)
13小时前关门了。
我试着做一个月度条形图,但是它总是把四月作为第一个月,而不是一月。有什么方法可以解决这个问题,使它在正确的顺序?

Number <- c(41,23,22,16,21,10,10,13,20,12,15,16,18,20,18,92,81,72,73,47,57,12,23,12,12,23,34,54,32,5,65,44,55,66,55,44)
 
Year <- c("2018","2018","2018","2018","2018","2018","2018","2018","2018","2018","2018","2018","2019","2019","2019","2019","2019","2019","2019","2019","2019","2019","2019","2019","2020","2020","2020","2020","2020","2020","2020","2020","2020","2020","2020","2020")
 
Month <- c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
 
library(ggplot2)
adultmonthly <- data.frame(Number,Year,Month)

ggplot(adultmonthly, aes(Year, Number, fill = Month)) +
  geom_bar(colour = "black", stat="identity", position = "dodge") +
  labs(title="Frequency of children affected")

llycmphe

llycmphe1#

你必须将变量Month转换为factor,转换的顺序是你想要的,在你的例子中,使用基常量month.abb是非常容易的:

library(ggplot2)

adultmonthly <- data.frame(Number, Year, Month)

adultmonthly$Month <- factor(adultmonthly$Month, levels = month.abb)

ggplot(adultmonthly, aes(Year, Number, fill = Month)) +
  geom_bar(colour = "black", stat = "identity", position = "dodge") +
  labs(title = "Frequency of children affected")

相关问题