R 如何在ggplot2中包含小中断

R 如何在ggplot2中包含小中断,r,ggplot2,R,Ggplot2,我想在我的图表中包括小刹车,这样完整的日期会在每个月初打印出来,而天数只会在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_

我想在我的图表中包括小刹车,这样完整的日期会在每个月初打印出来,而天数只会在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')
这个问题已经在中讨论过了,但我想知道是否同时发生了一些变化,因为如果我遵循建议的代码

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

我不确定你的错误是什么,因为这不是一个可复制的样品

下面的代码在我的电脑上运行,每周给你打勾

ggplot() +
     geom_line(data=df, aes(x=date, y=value)) +
     scale_x_date(date_breaks = "1 week", 
                   date_minor_breaks = "1 day",)
您可以使用
date\u 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")
您还可以通过使用
主题
层来改变蜱虫的美感。例如,更改为“下一步”将为您提供更长或更大的刻度

   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)

不是一个月的第一个月没有错误,我希望每天都有一个勾号。但是,只应标记月份。我编辑了我的答案。这是你想要的吗?lubridate::floor_Date谢谢是的,最后一个脚本就是我想要做的。事实上,我认为,
小破折号
画的刻度更小,这在美学上更吸引人。也许我遗漏了文档中的某些内容,但我并不完全清楚该属性是否在背景网格线上起作用。如果你想留下你答案的第一部分,那是因为我的问题可能不清楚,但实际上我只对最后一部分感兴趣。是的,我会留下它,但我驼背了你可能想要的东西,这就是为什么我在主题上包括了简介。
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")