我尝试绘制由于月份和年份引起的频率图
但是我的问题是x轴是字母顺序的顺序,而不是月份和年份(2018年12月,2019年1月,2019年2月等)的顺序
我试图将month列转换为Date,但是它使所有值都为null。我该怎么做?
library(ggplot2)
library(ggpubr)
theme_set(theme_pubr())
monthplot = data.frame(month = c("December 2018", "January 2019", "February 2019", "March 2019", "April 2019", "May 2019", "June 2019", "July 2019"), visits = c(96267, 59939, 48340, 56886, 37785, 56245, 38328, 25284))
#monthplot$month <- as.Date(monthplot$month, format = "%m %Y")
ggplot(monthplot, aes(x = month, y = visits)) +
geom_bar(fill = "#0073C2FF", stat = "identity") +
geom_text(aes(label = visits), vjust = -0.3) +
theme_pubclean()
答案 0 :(得分:2)
使用targetNode.OuterXml
在“月份”列中创建日期
lubridate
如果要更改日期显示方式,请使用monthplot <- monthplot %>%
mutate(date = lubridate::dmy(month, truncated = -1))
ggplot(monthplot, aes(x = date, y = visits)) +
geom_col(fill = "#0073C2FF") +
geom_text(aes(label = visits), vjust = -0.3) +
theme_pubclean()
并设置scale_x_date
和/或date_breaks
参数
答案 1 :(得分:1)
library(dplyr)
library(ggplot2)
library(ggpubr)
theme_set(theme_pubr())
monthplot = data.frame(month = c("December 2018", "January 2019", "February 2019", "March 2019", "April 2019", "May 2019", "June 2019", "July 2019"), visits = c(96267, 59939, 48340, 56886, 37785, 56245, 38328, 25284))
#monthplot$month <- as.Date(monthplot$month, format = "%m %Y")
## first add a date field
monthplot <-
monthplot %>%
mutate(date2 = paste('15', tolower(substr(month, 1, 3)), sep = '-')) %>%
mutate(date2 = paste(date2, gsub('[^0-9]', '', month), sep = '-')) %>%
mutate(date2 = as.Date(date2, '%d-%b-%Y'))
## then reorder your bars by that date field
ggplot(monthplot, aes(x = reorder(month, date2), y = visits)) +
geom_bar(fill = "#0073C2FF", stat = "identity") +
geom_text(aes(label = visits), vjust = -0.3) +
theme_pubclean() +
theme(axis.text.x = element_text(angle = 60, hjust = 1))