首页 > 解决方案 > 如何使用日期删除ggplot2中轴和区域图之间的空间

问题描述

我有我想用 ggplot2 绘制的数据,x 轴开始一个日期,y 轴一些值。因此,我的数据类似于:

library(data.table)
library(zoo) # Pour du traitement de données, par exemple pour les dates
library(ggplot2) # Pour du traitement de données, par exemple pour les dates

MWE <- data.table(id = seq(1, 2191), 
                        Periode = as.Date(c(as.Date("2010-01-01"):as.Date("2015-12-31"))),
                        VValue = rnorm(2191, mean = 400, sd = 60))

我可以使用这些代码行:

ggplot(data = MWE, 
       aes(x = Periode, y = VValue , color)) +
  geom_line(color = "Blue", size = 1) +
  scale_x_date(limits = c(as.Date("2012-01-01"), NA))

要得到这张照片:在此处输入图像描述

我希望我的情节从我正在考虑的第一个日期开始,因此要删除 x 轴上“2012”左侧的空格。

我看过这个问题,但是下面的代码:

  ggplot(data = MWE, 
         aes(x = Periode, y = VValue, color)) +
    geom_line(color = "Blue", size = 1) +
    scale_x_continuous(limits = c("2012-01-01",NA), expand = c(0, 0)) 

给我一个警告:

Error in as.Date.numeric(value) : 'origin' doit être spécifié

我没有设法解决这个问题,甚至origin=在我的参数中添加了一个。

我怎么能解决这个问题?

标签: rggplot2

解决方案


您必须指定expand = c(0,0)inscale_x_date因为您的 x 轴不是连续(数字)格式,而是日期格式:

ggplot(data = MWE, 
       aes(x = Periode, y = VValue , color)) +
  geom_line(color = "Blue", size = 1) +
  scale_x_date(limits = c(as.Date("2012-01-01"), NA), expand = c(0,0))

在此处输入图像描述


推荐阅读