如何在 ggplot2 中每 3 或 6 个月显示日期 x 轴标签

ahb*_*bon 11 r ggplot2

我用下面的代码生成一个图:

ggplot(reshaped_median, aes(x= Month_Yr, y = value))+ 
  geom_line(aes(color = Sentiments)) + 
  geom_point(aes(color = Sentiments)) + 
  labs(title = 'Change in Sentiments (in median)', x = 'Month_Yr', y = 'Proportion of Sentiments %') + 
  theme(axis.text.x = element_text(angle = 60, hjust = 1))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

但正如您所注意到的,x 轴上的日期标签太密集,因此如果我想要它每季度或每半年(每 3 或 6 个月)显示日期。

来自的值的Month_Yr格式为%Y-%m

我怎么能这么做呢?谢谢。

Duc*_*uck 13

首先转换日期:df$Month_Yr <- as.Date(as.yearmon(df$Month_Yr))

然后使用这个可以解决问题:

ggplot(reshaped_median, aes(x= Month_Yr, y = value))+ 
  geom_line(aes(color = Sentiments)) + 
  geom_point(aes(color = Sentiments)) + 
  #Here you set date_breaks  ="6 month" or what you wish
  scale_x_date(date_labels="%b-%d",date_breaks  ="3 month")+
  labs(title = 'Change in Sentiments (in median)', x = 'Month_Yr', y = 'Proportion of Sentiments %') + 
  theme(axis.text.x = element_text(angle = 60, hjust = 1))
Run Code Online (Sandbox Code Playgroud)


Pau*_*pen 5

这是另一种方法。您scale_x_date可以轻松地操纵 x 轴上的断点。

library(ggplot2)
library(tibble)

data <- tibble(
  Month_Yr = seq.Date(from = as.Date("2010/01/01"), to =  as.Date("2020/01/31"), by = "month"),
  Value = runif(121, min = 0, max = 150)
)


p <- ggplot(data = data, aes(x = Month_Yr, y = Value)) + 
  geom_point() +
  theme(axis.text.x = element_text(angle = 60, hjust = 1)) +
  scale_x_date(date_breaks = "6 months")
p
Run Code Online (Sandbox Code Playgroud)