【问题标题】:How to include minor breaks in ggplot2如何在 ggplot2 中包含小中断
【发布时间】:2016-07-24 00:30:44
【问题描述】:

我想在我的图表中加入一些小刹车,以便在每个月初打印完整的日期,并且在 x 轴上只用一个勾号来标记日期。 我现在所拥有的不会检索错误,但输出不是我想要的,因为这些天没有刻度。

library(ggplot2)

df <- data.frame(date=as.Date(1:60,origin = "1970-01-01"),value=rnorm(60,4,3))
str(df)
ggplot()+
  geom_line(data=df, aes(x=date, y=value))+
  scale_x_date(date_breaks = 'month', date_minor_breaks = 'day')

会话:

other attached packages:
[1] scales_0.4.0  cowplot_0.6.2 ggplot2_2.1.0 dplyr_0.5.0   zoo_1.7-13  

这个问题已经在Formatting dates with scale_x_date in ggplot2 中讨论过,但我想知道在此期间是否发生了一些变化,因为如果我按照建议的代码进行操作

scale_x_date(breaks = "1 month", minor_breaks = "1 week", labels=date_format("%B")) 

我实际上得到了一个错误

> ggplot()+
+   geom_line(data=df, aes(x=date, y=value))+
+   scale_x_date(breaks = "1 month", minor_breaks = "1 week", labels=date_format("%B"))
Error in strsplit(unitspec, " ") : non-character argument

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我不确定您的错误是什么,因为这不是可重现的样本。

    以下代码可在我的计算机上运行,​​并为您提供每周刻度。

    ggplot() +
         geom_line(data=df, aes(x=date, y=value)) +
         scale_x_date(date_breaks = "1 week", 
                       date_minor_breaks = "1 day",)
    

    您可以使用date_labels 参数更改每周标签的格式,例如,使用%D 会为您提供m/d/y,如下所示。

    ggplot() +
         geom_line(data=df, aes(x=date, y=value)) +
         scale_x_date(date_breaks = "1 week", 
                        date_minor_breaks = "1 day",
                        date_labels = "%D")
    

    您可以使用theme 层更改刻度的美感。例如,更改为以下将为您提供更长或更大的刻度。

       ggplot() +
         geom_line(data=df, aes(x=date, y=value)) +
         scale_x_date(date_breaks = "1 week", 
                       date_minor_breaks = "1 day",) +
        theme(axis.text.x=element_text(size=10),
              axis.ticks = element_line(size = .5),
              axis.ticks.length = unit(.2, "cm"))
    

    已编辑:根据您的评论,我认为这就是您想要的。不知道为什么,但对我来说它看起来有点“丑陋”。希望这可以帮助。

    library(lubridate) 
    not_first_of_the_month<- which(duplicated(floor_date(df$date, "month")))
    xlabels <- as.character(df$date)
    xlabels[not_first_of_the_month] <-rep("", length(not_first_of_the_month))
    
    ggplot() +
         geom_line(data=df, aes(x=date, y=value)) +
                   scale_x_date(breaks = df$date,
                                labels = xlabels,
                   date_minor_breaks = "1 day")
    

    【讨论】:

    • 没有错误我希望每天有一个刻度线。但是,应该只标记月份。
    • 我编辑了我的答案。这给了你想要的东西吗?
    • ?lubridate::floor_date
    • 谢谢,是的,最后一个脚本是我想要做的。我实际上认为minor_breaks 绘制了更小的刻度,这在美学上会更具吸引力。也许我错过了文档中的某些内容,但我并不完全清楚该属性在背景网格线上运行。如果您想留下答案的第一部分,那是因为我的问题可能不清楚,但实际上我只对最后一部分感兴趣。
    • 是的,我会留下它,但我预感到你可能想要的东西,这就是为什么我在主题中加入了简介。
    猜你喜欢
    • 1970-01-01
    • 2015-07-10
    • 2013-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多