在ggplot中指定月份以获取季度数据

时间:2019-06-14 05:15:56

标签: r ggplot2 tidyverse

我有此数据:

test_data <- structure(list(region = c("Goulburn", "Goulburn", "Goulburn", 
"Goulburn", "Goulburn", "Goulburn", "Goulburn", "Goulburn", "Goulburn", 
"Goulburn", "Goulburn", "Goulburn", "Goulburn", "Goulburn", "Goulburn", 
"Goulburn", "Goulburn", "Goulburn", "Goulburn", "Goulburn", "Goulburn", 
"Goulburn", "Goulburn", "Goulburn", "Goulburn", "Goulburn", "Goulburn", 
"Goulburn", "Goulburn", "Goulburn", "Goulburn", "Goulburn", "Goulburn", 
"Goulburn"), month = c("40513", "40603", "40695", "40787", "40878", 
"40969", "41061", "41153", "41244", "41334", "41426", "41518", 
"41609", "41699", "41791", "41883", "41974", "42064", "42156", 
"42248", "42339", "42430", "42522", "42614", "42705", "42795", 
"42887", "42979", "43070", "43160", "43252", "43344", "43435", 
"43525"), unemployment_rate = c(7.4, 5.6, 4.6, 4.2, 4.3, 4.5, 
4.7, 5.3, 5.2, 5.8, 5.9, 5.6, 6.1, 7.8, 8.8, 8.8, 8, 6.2, 4.9, 
5, 5.4, 5.5, 5.6, 5.2, 5.4, 6.2, 6.5, 7.4, 7.2, 6.5, 6.9, 7.1, 
7.6, 7.3), month2 = structure(c(14944, 15034, 15126, 15218, 15309, 
15400, 15492, 15584, 15675, 15765, 15857, 15949, 16040, 16130, 
16222, 16314, 16405, 16495, 16587, 16679, 16770, 16861, 16953, 
17045, 17136, 17226, 17318, 17410, 17501, 17591, 17683, 17775, 
17866, 17956), class = "Date")), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -34L))

并放入此ggplot中:

ggplot(test_data, aes(month2, unemployment_rate)) +
  geom_line() + geom_point() + scale_colour_discrete(name  ="SA2") + theme(legend.position="bottom") +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  labs(title = "Unemployment rate", x = NULL, y = "Unemployment rate (%)") + 
  scale_x_date(date_breaks = "3 months", date_labels = "%m-%Y")

给我这张图enter image description here

我如何更改(翻转)y轴所示的月份?我希望他们显示与数据(03、06、09、12)或什至(3月,6月,9月,12月)相同的东西,以及年份(所以03-2019或Mar-2019)吗?

我已经尝试了一些方法,但是无法正常工作。

1 个答案:

答案 0 :(得分:3)

这是一种方法,在第一个日期指定scale_x_date(limits,并删除expand为零的填充:

ggplot(test_data, aes(month2, unemployment_rate)) +
  geom_line() + geom_point() + 
  scale_colour_discrete(name  ="SA2") + 
  scale_x_date(limits = c(as.Date(min(test_data$month2)), NA),
               expand = expand_scale(0), minor_breaks = NULL,
               date_breaks = "3 months", date_labels = "%m-%Y") +
  coord_cartesian(clip = "off") +
  theme(legend.position="bottom") +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  labs(title = "Unemployment rate", x = NULL, y = "Unemployment rate (%)")

enter image description here