r - 如何在 ggplot2 中按时间顺序排列月份而不是写出月份?

标签 r ggplot2

我正在尝试绘制计数 v/s 月

ggplot(dat, aes(x=month, y=count,group=region)) +
    geom_line(data=mcount[mcount$region == "West coast", ],colour="black",stat="identity", position="dodge")+
     geom_point(data=mcount[mcount$region == "West coast", ],colour="black", size=2, shape=21, fill="white")+
     theme_bw()+
     theme(legend.key = element_rect(colour = "black")) +
     guides(fill = guide_legend(override.aes = list(colour = NULL)))+
     ggsave("test.png",width=6, height=4,dpi=300)

enter image description here

但是我想按时间顺序排列从 1 月到 12 月的月份。如果不写出所有月份,我怎么办?

输出
structure(list(region = structure(c(6L, 6L, 6L, 6L, 6L, 6L, 6L, 
6L, 6L, 6L, 6L, 6L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 
5L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 
4L, 4L, 4L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 
3L), .Label = c("West coast", "Arizona", "Front range", "Flash flood alley", 
"Mississippi valley", "Appalachians"), class = "factor"), month = structure(c(1L, 
2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 1L, 4L, 12L, 11L, 
5L, 2L, 9L, 8L, 6L, 10L, 3L, 7L, 8L, 10L, 5L, 1L, 6L, 7L, 4L, 
6L, 8L, 2L, 1L, 7L, 5L, 3L, 11L, 12L, 9L, 10L, 2L, 7L, 3L, 6L, 
12L, 11L, 10L, 9L, 4L, 1L, 11L, 4L, 2L, 1L, 12L, 9L, 3L, 8L, 
5L, 6L, 10L, 7L, 5L, 8L, 11L, 12L, 4L, 3L, 9L, 2L), .Label = c("Apr", 
"Dec", "Oct", "Mar", "May", "Jul", "Sep", "Jun", "Nov", "Aug", 
"Jan", "Feb"), class = "factor"), count = c(566, 545, 427, 751, 
357, 399, 568, 433, 454, 347, 511, 251, 267, 207, 167, 142, 417, 
109, 117, 373, 207, 130, 125, 145, 7, 14, 2, 2, 7, 3, 107, 74, 
135, 48, 80, 53, 117, 125, 59, 53, 103, 30, 21, 18, 8, 22, 26, 
37, 20, 5, 11, 1, 96, 29, 109, 8, 33, 53, 6, 1, 5, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 0)), .Names = c("region", "month", "count"), row.names = c(NA, 
-72L), class = c("data.table", "data.frame"))

最佳答案

使用内置month.namemonth.abb变量以按正确的顺序指定因子的水平。在这种情况下,您有缩写词 month.abb是合适的。

your_data$month = factor(your_data$month, levels = month.abb)
我认为以正确的顺序创建因子是最好的方法,但您也可以使用 limits 对轴进行排序。离散尺度的参数(有关更多信息,请参阅 ?discrete_scale)。
+ scale_x_discrete(limits = month.abb)
语言环境
如果您使用的是非英语语言环境,则可以使用一些日期格式构建自己的月份名称常量(基本上是从 Brian Ripley in this R-Help thread 中窃取的):
 month.name.loc = format(ISOdate(2004, 1:12, 1), "%B")
 month.abb.loc  = format(ISOdate(2004, 1:12, 1), "%b")
如果您想使用与您所在地区不同的月份名称/缩写,请使用 withr包很有用。

关于r - 如何在 ggplot2 中按时间顺序排列月份而不是写出月份?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36020146/

相关文章:

r - 如何在 R 中加速 `expand.grid()`?

r - 如何制作堆积面积图?

r - 多面 ggplot 华夫饼图中的手动色标

r - 在地理空间分析中将多多边形转变为单点

r - 如何在R中创建tar.gz文件?

在序列中每隔 n 个重复第 n 个元素

r - 我可以指示 Predict 忽略 R 中的错​​误行吗?

r - 如何从ggplot2获取geom_vline和facet_wrap以在函数内工作

r - 如何绘制一个因子水平作为 geom_col/geom_area 的基础

mysql - 在 MySQL 或 R 中对分析数据进行下采样