ggplot2日期对象在水平轴上舍入

时间:2015-01-21 15:18:27

标签: r ggplot2

当我在ggplot2中绘制时间序列对象时,其中水平轴是日期对象(月末日期),我发现日期以某种方式获得"四舍五入"到下个月初。例如," 2014年1月31日"将出现在" 2014年2月1日"。下面提供一个例子。我怎样才能解决这个问题?谢谢!

fruits.sold <- data.frame(Date=c("1/31/2014", "1/31/2014", "2/28/2014", "2/28/2014", "3/31/2014", "3/31/2014"), 
                   Fruit=c("Apple", "Banana", "Apple", "Banana", "Apple", "Banana"), 
                   Sold=c(200, 300, 250, 350, 300, 400))

fruits.sold$Date <- as.Date(fruits.sold$Date, "%m/%d/%Y")

qplot(Date, Sold, colour=Fruit, data=fruits.sold)

1 个答案:

答案 0 :(得分:2)

您可以使用scale_x_date直接指定:

p <- qplot(Date, Sold, colour=Fruit, data=fruits.sold)
p + scale_x_date(breaks=fruits.sold$Date,
            labels=format(fruits.sold$Date,
                      format="%B %d %Y"))

enter image description here

相关问题