R + ggplot2:如何从x轴隐藏缺失日期? [英] R + ggplot2: how to hide missing dates from x-axis?

查看:123
本文介绍了R + ggplot2:如何从x轴隐藏缺失日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下简单的日期 - 值对数据框,其中某些日期在序列中缺失(即1月12日至1月14日)。绘制点时,它会在x轴上显示这些缺失的日期,但没有与这些日期对应的点。我想防止这些缺失的日期出现在x轴上,以便点序列没有中断。有关如何做到这一点的任何建议?谢谢!

  dts < -  c(as.Date(c('2011-01-10','2011-01-11 ','2011-01-15','2011-01-16')))
df< - data.frame(dt = dts,val = seq_along(dts))
ggplot(df ,aes(dt,val))+ geom_point()+
scale_x_date(format ='%d%b',major ='days')

解决方案

然后将日期数据转换为一个因子。目前,ggplot正在解释你所告诉数据的意义 - 连续的日期范围。您不需要这个比例,您需要一个分类比例:

  require(ggplot2)
dts < - as.Date(c('2011-01-10','2011-01-11','2011-01-15','2011-01-16'))
df< - data.frame (dt = dts,val = seq_along(dts))
ggplot(df,aes(dt,val))+ geom_point()+
scale_x_date(format ='%d%b',major ='天')



  df < -  data.frame(dt =因子(格式(dts,format ='%d%b')),
val = seq_along(dts))
ggplot (df,aes(dt,val))+ geom_point()

产生:



Say we have the following simple data-frame of date-value pairs, where some dates are missing in the sequence (i.e. Jan 12 thru Jan 14). When I plot the points, it shows these missing dates on the x-axis, but there are no points corresponding to those dates. I want to prevent these missing dates from showing up in the x-axis, so that the point sequence has no breaks. Any suggestions on how to do this? Thanks!

dts <- c(as.Date( c('2011-01-10', '2011-01-11', '2011-01-15', '2011-01-16')))
df <- data.frame(dt = dts, val = seq_along(dts)) 
ggplot(df, aes(dt,val)) + geom_point() + 
        scale_x_date(format = '%d%b', major='days')

解决方案

Turn the date data into a factor then. At the moment, ggplot is interpreting the data in the sense you have told it the data are in - a continuous date scale. You don't want that scale, you want a categorical scale:

require(ggplot2)
dts <- as.Date( c('2011-01-10', '2011-01-11', '2011-01-15', '2011-01-16'))
df <- data.frame(dt = dts, val = seq_along(dts)) 
ggplot(df, aes(dt,val)) + geom_point() + 
        scale_x_date(format = '%d%b', major='days')

versus

df <- data.frame(dt = factor(format(dts, format = '%d%b')), 
                  val = seq_along(dts)) 
ggplot(df, aes(dt,val)) + geom_point()

which produces:

Is that what you wanted?

这篇关于R + ggplot2:如何从x轴隐藏缺失日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆