【问题标题】:Removing gap between ggplot y-axis and first x-value消除 ggplot y 轴和第一个 x 值之间的间隙
【发布时间】:2014-10-19 13:13:04
【问题描述】:

我需要移除 x 轴上 1950 年之前的间隙。

我曾尝试使用scale_x_continuous,但这会导致:

Error: Discrete value supplied to continuous scale

我相信这一定与数据的日期格式有关。

示例数据:

x      y                date
1    -631152000 -1.018 1950-01-01 01:32:40
2    -628473600 -1.143 1950-02-01 01:32:40
3    -626054400 -1.290 1950-03-01 01:32:40
4    -623376000 -1.061 1950-04-01 01:32:40
5    -620784000 -1.416 1950-05-01 01:32:40
6    -618105600 -1.372 1950-06-01 01:32:40
7    -615513600 -1.334 1950-07-01 01:32:40
8    -612835200 -1.050 1950-08-01 01:32:40
9    -610156800 -0.578 1950-09-01 01:32:40
10   -607564800 -0.395 1950-10-01 01:32:40

用于创建情节的代码:

Plot <- ggplot(d2,aes(x = date,
              y = y)) + 
  geom_area(data=subset(d2, y<=0), fill="blue") + 
  geom_area(data=subset(d2, y>=0), fill="red") + 
  scale_y_continuous(name = "MEI")+
  xlab("Year")+
  theme(axis.text.y   = element_text(size=24),
        axis.text.x   = element_text(size=24),
        axis.title.y  = element_text(size=24),
        axis.title.x  = element_text(size=24),
        panel.background = element_blank(),
        panel.grid.major = element_line(colour = "grey"), 
        strip.background = element_blank(),
        panel.border = element_rect(colour = "black", fill = NA),
        axis.line = element_line(colour = "black"))

任何帮助将不胜感激!!!

【问题讨论】:

    标签: r date ggplot2 axis-labels


    【解决方案1】:

    您可以使用scale_x_datetimeexpand 参数来删除轴和数据开头之间的空间。 (您也可以在 scale_y(x)_continuous 等中使用它...)

    # your data - tweaked to include pos / neg y values
    d2 <- read.table(text="x      y                date
    1    -631152000 -1.018 '1950-01-01 01:32:40'
    2    -628473600 -1.143 '1950-02-01 01:32:40'
    3    -626054400 -1.290 '1950-03-01 01:32:40'
    4    -623376000 -1.061 '1950-04-01 01:32:40'
    5    -620784000 -1.416 '1950-05-01 01:32:40'
    6    -618105600 1.372 '1950-06-01 01:32:40'
    7    -615513600 1.334 '1950-07-01 01:32:40'
    8    -612835200 1.050 '1950-08-01 01:32:40'
    9    -610156800 0.578 '1950-09-01 01:32:40'
    10   -607564800 0.395 '1950-10-01 01:32:40'", header=TRUE)
    
    # create date class and tag for y being pos / negative
    d2$date <- as.POSIXct(d2$date)
    d2$tag <- d2$y < 0
    
    library(ggplot2)  
    
    ggplot(d2,aes(x = date, y = y, fill=tag)) + 
                          geom_area() + 
                          scale_y_continuous(name = "MEI")+
                          scale_x_datetime(expand=c(0,0))
    

    【讨论】:

    • 数据类型为'POSIXct'
    猜你喜欢
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    • 2020-06-03
    相关资源
    最近更新 更多