简体   繁体   English

x轴为mm-dd时使用ggplot2编辑轴刻度标签

[英]Editing axis tick labels with ggplot2 when x-axis is mm-dd

I have a dataset where the x-axis is a date, but it is only mm-dd (no year). 我有一个数据集,其中x轴是日期,但只有mm-dd(没有年份)。 I am using year as a group variable as I am trying to show a YOY change on the same plot. 我正在使用year作为组变量,因为我试图在同一图上显示YOY的变化。 The x-axis labeling is too crowded and I'd like to limit the tick mark labels so that not every date is shown. X轴标签太拥挤了,我想限制刻度线标签,以便不显示每个日期。 This could be every other day, every third day, one day a week -- any of these would work. 可能是隔天一次,隔三天一次,一周一次-这些中的任何一个都可以工作。

I have tried a few solutions but cannot get them to work, I'm assuming because my x-axis is not a Date, but a character. 我尝试了一些解决方案,但无法使其正常工作,因为我的x轴不是日期,而是一个字符,所以我想。 (Previous to arriving at this mm-dd solution for the x-axis, I tried plotting the x-axis with a yyyy-mm-dd Date format, but was unsuccessful in figuring out how to get ggplot2 to ignore the "yyyy" part.) (在获得针对x轴的mm-dd解决方案之前,我曾尝试使用yyyy-mm-dd Date格式绘制x轴,但未能弄清楚如何使ggplot2忽略“ yyyy”部分而未能成功)

An example: 一个例子:

myDF <- data.frame(
        myDate = format(seq(as.Date("2014-02-01"), 
                 length=28, by="1 day"), "%m-%d"),
        myVar = sample(100,28),
        myGroup = sample(2,28,TRUE)
                   )
head(myDF)

  myDate myVar myGroup
  02-01    87       1
  02-02    34       1
  02-03    48       2
  02-04    59       1
  02-05    98       1
  02-06    18       2

ggplot(myDF, aes(myDate, myVar, group=myGroup, color=as.factor(myGroup))) + 
geom_line() 

此处的所有内容都是正确的,除了刻度线太紧了。

I have tried: 我努力了:

ggplot(myDF, aes(myDate, myVar, group=myGroup, color=as.factor(myGroup))) +   
geom_line() + scale_x_discrete(breaks = c(1,10,20))

This appears to confuse ggplot since the labels disappear completely. 这似乎使ggplot感到困惑,因为标签完全消失了。 (Same result with a seq() attempt.) (尝试seq()的结果相同。)

I have also tried: 我也尝试过:

ggplot(myDF, aes(myDate, myVar, group=myGroup, color=as.factor(myGroup))) + 
geom_line() + scale_x_date(breaks = "1 week")

This throws an error re: myDate not being a Date. 这将引发错误:myDate不是日期。

I've already switched the format of the tick labels to be vertical, but it is still too crowded on the plot. 我已经将刻度标签的格式切换为垂直,但是在绘图上仍然太拥挤了。

Any tips would be very much appreciated. 任何提示将不胜感激。 Thanks! 谢谢!

If you want to use myDate variable without the year (as character) then one solution would be to use scale_x_discrete() and then provide myDF$myDate as breaks= argument and select sequence of values you want to show. 如果要使用不带年份(作为字符)的myDate变量,则一种解决方案是使用scale_x_discrete() ,然后提供myDF$myDate作为breaks=参数,然后选择要显示的值序列。 In this example I selected every 7th value. 在此示例中,我每7个值选择一次。

ggplot(myDF, aes(myDate, myVar, group=myGroup, color=as.factor(myGroup))) +   
      geom_line() + scale_x_discrete(breaks = unique(myDF$myDate)[seq(1,28,7)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM