错误:使用ggplot时将离散值提供给连续刻度

时间:2018-08-29 11:33:10

标签: r date ggplot2 plot format

我绘制了一个散点图,在y轴上显示了频率量,在x轴上显示了日期(例如2012-07)。另外,我在绘图中添加了垂直线(向量r1)。绘图后,出现错误消息

  

错误:将离散值提供给连续刻度

我的数据框 df1 如下:

date         amount
2012-07          2
2012-08          4
2012-09          4
2012-10          3
2012-11          2
2012-12          3
2013-01          5 
2013-02          4
2013-03          3
2013-04          2
2013-05          1
2013-06          4
2013-07          3

我的垂直线在向量r1中,如下所示:

1
2
4
6
7
9

数字1等于我的df1 $ date的第一个条目,数字2等于第二个条目,依此类推。

ggplot(df1, aes(x=date,y=amount, color=gr)) +    
            geom_vline(xintercept=as.numeric(r1), alpha=0.5) +    
            geom_point()

我猜这是由于以下事实造成的:r1的值类似于1、2、5,但我的x轴采用日期格式,因此无法一起使用。所以数字1代表我在向量r1中的第一个日期,数字2代表第二个日期,依此类推...等等,有什么办法可以将这个r1矢量更改为我的对应日期?谢谢!

2 个答案:

答案 0 :(得分:0)

您可以先使用as.Date将日期列转换为格式正确的日期。由于只有蛾子可用,因此我将日期设置为每月的第一天,但​​您也可以指定第15天。

df1$date <- as.Date(paste0(df1$date, "-01"))

现在我们绘制数据时,x轴的格式很好:

library(ggplot2)

ggplot(df1, aes(date, amount)) +
  geom_point()

enter image description here

对于垂直线,从data.frame中提取所需的日期,然后将其添加到绘图中:

ggplot(df1, aes(date, amount)) +
  geom_point() + 
  geom_vline(xintercept = df1$date[r1], alpha = 0.5)

enter image description here

如果您切换通话顺序,现在也可以使用

ggplot(df1, aes(date, amount)) + 
  geom_vline(xintercept = df1$date[r1], alpha = 0.5) +
  geom_point()

数据

df1 <- 
  structure(list(date = c("2012-07", "2012-08", "2012-09", "2012-10", "2012-11", 
                          "2012-12", "2013-01", "2013-02", "2013-03", "2013-04", 
                          "2013-05", "2013-06", "2013-07"), 
                 amount = c(2L, 4L, 4L, 3L, 2L, 3L, 5L, 4L, 3L, 2L, 1L, 4L, 3L)), 
            class = "data.frame", row.names = c(NA, -13L))

r1 <- c(1, 2, 4, 6, 7, 9)

答案 1 :(得分:0)

正如kath所提到的,最好将日期和行更改为日期格式。在这里,我使用lubridate

library(ggplot2)
library(dplyr)
library(lubridate)
df1 <- read.table(header = T, stringsAsFactors = FALSE, text = 
"date         amount
2012-07          2
2012-08          4
2012-09          4
2012-10          3
2012-11          2
2012-12          3
2013-01          5 
2013-02          4
2013-03          3
2013-04          2
2013-05          1
2013-06          4
2013-07          3"
)

r1 <- c(1,2,4,6,7,9)

df2 <- df1 %>% mutate(line = ifelse(row_number(date) %in% r1, date, NA)) %>% 
  mutate(date = ymd(date, truncated = 2), line = ymd(line, truncated = 2))

ggplot(df2, aes(x = date,y = amount, color = amount)) +    
  geom_vline(aes(xintercept = line), alpha=0.5) +    
  geom_point()

注意:由于col不在示例数据中,因此我将amount参数更改为gr