我有一个这样的数据框(按日期顺序):
freq date
3 Jan-18
2 Feb-18
42 Mar-18
2 Apr-18
4 May-18
但是,当我使用以下代码绘制它时,它不会按照保存在数据框中的顺序进行排序。相反,它按字母顺序绘制它们(参见 x 轴)。如何解决这个问题,以便按照保存在数据框中的顺序完成绘图?
请注意,日期列的类型为字符,这可能是原因,但是将其更改为日期格式很棘手,因为没有日期,并且当您这样做时,它会更改,例如Jun-18 到 01-1918-06,这在图表上看起来不太好。所以,如果可能的话,我会尝试在不将其更改为日期格式的情况下执行此操作。
ggplot(df, aes(x = date, y = freq)) +
geom_point()
答案 0 :(得分:1)
1) 假设最后的 Note 中显示的数据可重复显示,将数据转换为带有 yearmon 索引的动物园系列(可以表示没有一天的年份和月份),在这种情况下,它是直接使用 autoplot.zoo
。如果您想要线图,请省略 geom 参数。
library(ggplot2)
library(zoo)
z <- read.zoo(df, index = "date", FUN = as.yearmon, format = "%b-%y")
autoplot(z, geom = "point") + scale_x_yearmon()
2) 这也有效:
library(dplyr)
library(ggplot2)
library(zoo)
df %>%
mutate(date = as.yearmon(date, format = "%b-%y")) %>%
ggplot(aes(date, freq)) + geom_point() + scale_x_yearmon()
Lines <- "
freq date
3 Jan-18
2 Feb-18
42 Mar-18
2 Apr-18
4 May-18"
df <- read.table(text = Lines, header = TRUE)
答案 1 :(得分:1)
另一种方式,如果数据显示为示例可能是:
library(dplyr)
#Code
df %>%
mutate(date=factor(date,levels = unique(date),ordered = T)) %>%
ggplot(aes(x=date,y=freq))+
geom_point()
输出:
或者格式化日期变量:
#Code2
df %>%
mutate(date=as.Date(paste0(date,'-01'),'%b-%y-%d')) %>%
ggplot(aes(x=date,y=freq))+
geom_point()+
scale_x_date(date_labels = '%b-%y')+
ggtitle('My title')
输出:
使用的一些数据:
#Data
structure(list(freq = c(3L, 2L, 42L, 2L, 4L), date = c("Jan-18",
"Feb-18", "Mar-18", "Apr-18", "May-18")), class = "data.frame", row.names = c(NA,
-5L))
答案 2 :(得分:0)
如果您不想依赖 zoo 包,您可以简单地选择一年(例如 2021 年),并且示例中日期列的转换工作正常。然后,您可以指定日期在 ggplot2 的 scale_x_date()
中的显示方式。 Here is how it looks like.
library(ggplot2)
df <- read.table(header = T, text = "
freq date
3 Jan-18
2 Feb-18
42 Mar-18
2 Apr-18
4 May-18")
df$date <- as.Date(paste0(df$date, "-2021"), format = "%B-%d-%Y")
ggplot(df, aes(date, y = freq)) +
geom_point() +
theme_bw() +
labs(x = "Date", y = "Frequency") +
scale_x_date(date_breaks = "2 weeks", date_labels = "%d-%b") +
theme(axis.text.x = element_text(angle = 45, vjust = 0.5))