ggplot2中的date_minor_breaks

3
我是一个ggplot2的初学者。我无法使用date_minor_breaks在x轴上显示季度“刻度”。
这是我的代码:
x<-c(seq(1:12))
time<-c("2010Q1","2010Q2","2010Q3","2010Q4","2011Q1","2011Q2", "2011Q3","2011Q4","2012Q1","2012Q2","2012Q3","2012Q4")
z<-data.frame(type = x,time = time)
z$time = as.yearqtr(z$time)
z$time = as.Date(z$time)
ggplot(data = z, aes(x=time,y=type)) +
geom_point() + 
scale_x_date(date_labels = "%Y",date_minor_breaks = "3 months",name = "Year") +
theme_tufte() +
theme(legend.position = "none")

我在SO 使用ggplot2中的scale_x_date格式化日期https://github.com/hadley/ggplot2/issues/542上研究了这个主题,并发现有一些关于此主题的问题报告。然而,由于我才开始使用ggplot2仅6天,所以我并没有完全跟上关于ggplot2的更改对话。

这是我得到的图表(它没有任何刻度)...

enter image description here

这是一个由Excel生成的带有“刻度线”的样本图表。请忽略值,因为我创建这个Excel图表的目的是为了演示我正在寻找的东西 - 即“季度刻度线”。我会感激你的帮助。

enter image description here

2个回答

7
你可能需要每三个月进行一次主要的间断,然后使用空格填充标签以产生主要(有标签)和次要(无标签)刻度线的假象。请参见此答案获取另一个示例。
首先手动为每个季度的刻度线制作间断。
breaks_qtr = seq(from = min(z$time), to = max(z$time), by = "3 months")

然后制作年份标签,并在每个数字后面加上三个空格。
labels_year = format(seq(from = min(z$time), to = max(z$time), by = "1 year"), "%Y")
labs = c(sapply(labels_year, function(x) {
    c(x, rep("", 3))
    }))

现在可以使用 scale_x_date 中的 labelsbreaks 参数来使用间隔和标签。请注意,我没有使用 date_labelsdate_breaks
ggplot(data = z, aes(x=time,y=type)) +
    geom_point() + 
    scale_x_date(labels = labs, breaks = breaks_qtr, name = "Year") +
    theme_tufte() +
    theme(legend.position = "none")

enter image description here


0

你还应该定义你的(主要的)日期分割点:

ggplot(data = z, aes(x=time, y=type)) +
  geom_point() + 
  scale_x_date(date_breaks = "1 year", name = "Year", date_minor_breaks="3 months",
               limits = c(as.Date(as.yearqtr("2009Q4")),
                          as.Date(as.yearqtr("2013Q2"))),
               expand=c(0,0), date_labels = "%Y") +
      theme(legend.position = "none")

还有一些其他“花哨”的东西可以将次要刻度与主要刻度对齐(我猜有更好的方法来做到这一点,但这个方法有效)。

enter image description here


刻度在哪里?我认为你看到的是网格线而不是刻度。请参见我上面问题中的Excel版本——它没有网格线,但有刻度... - watchtower
那么你可以将 date_breaks 定义为 3 个月,然后手动定义标签并留下空白。 - Huub Hoofs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接