2011-07-10 30 views
9

我正在绘制ggplot2中的值〜日期(R中)。我有以下代码。正如你所看到的,ggplot2在我的数据中所增加的x轴上添加了更多的中断。我只想每次在我的数据框中有一个数据点时都有x标签。我如何强制ggplot2仅在my.dates的值处显示中断?似乎有对scale_x_dateggplot2和R中的scale_x_date的中断

require(ggplot2) 
my.dates = as.Date(c("2011-07-22","2011-07-23", 
        "2011-07-24","2011-07-28","2011-07-29")) 
my.vals = c(5,6,8,7,3) 
my.data <- data.frame(date =my.dates, vals = my.vals) 
plot(my.dates, my.vals) 
p <- ggplot(data = my.data, aes(date,vals))+ geom_line(size = 1.5) 
p <- p + scale_x_date(format="%m/%d", ' ') 
p 
没有“休息”的说法

enter image description here

回答

14

一种方法是治疗x轴的数值,并设置休息和标签美学与scale_x_continuous()

ggplot(my.data, aes(as.numeric(date), vals)) + 
    geom_line(size = 1.5) + 
    scale_x_continuous(breaks = as.numeric(my.data$date) 
        , labels = format(my.data$date, format = "%m/%d")) 

虽然7/24到7/28之间的间隔在我看来有点奇怪。但是,我认为这就是你想要的?如果我误解了,请告诉我。

EDIT

如上所述,我并不激动与突破了搜索的方式,特别是与在背景中的灰色网格。这里有一种方法来维护矩形网格并只标记我们有数据的点。你可以在ggplot调用中完成这一切,但我认为在ggplot之外进行处理更容易。首先,创建一个包含与日期对应的数字序列的向量。然后,我们将更新相应的标签,并与" "更换NA条目,以防止任何从x轴这些条目被描绘:

xscale <- data.frame(breaks = seq(min(as.numeric(my.data$date)), max(as.numeric(my.data$date))) 
         , labels = NA) 

xscale$labels[xscale$breaks %in% as.numeric(my.data$date)] <- format(my.data$date, format = "%m/%d") 
xscale$labels[is.na(xscale$labels)] <- " " 

这给我们的东西,看起来像:

breaks labels 
1 15177 07/22 
2 15178 07/23 
3 15179 07/24 
4 15180  
5 15181  
6 15182  
7 15183 07/28 
8 15184 07/29 

然后可以传递给规模是这样的:

scale_x_continuous(breaks = xscale$breaks, labels = xscale$labels)

+0

非常感谢。第一部分解决了我的问题。你有没有机会知道我可以如何保持X轴断裂,但删除其网格线? – Mark

+2

@Mark - 'opts(panel.grid.major = theme_blank(),panel.grid.minor = theme_blank())'应该可以做到。 – Chase

+1

在'ggplot2 1.0.0'中抛出'错误:提供给连续标度的离散值'。 – MYaseen208