gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 09:23:46 24 4
gpt4 key购买 nike

我正在尝试绘制计数 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com