代码之家  ›  专栏  ›  技术社区  ›  ah bon

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

  •  0
  • ah bon  · 技术社区  · 5 年前

    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))
    

    enter image description here

    来自的值 Month_Yr 有格式吗 %Y-%m

    我怎么能这么做?谢谢。

    1 回复  |  直到 5 年前
        1
  •  4
  •   ah bon    5 年前

    第一次转换日期依据: 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))
    
        2
  •  2
  •   Paul van Oppen    5 年前

    scale_x_date

    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