简体   繁体   中英

Add point to line graph in ggplot when x axis is in Date format

I built a line graph using ggplot that shows changes in two different types of monetary contributions over years for a company. I am trying to add a red dot on the graph during certain years to denote specific events. Since my x axis is in Date format, I am struggling to use geom_point to add in the dot.

My data looks something like this:

money1       money2       year
6000         8000         2011-01-01
7000         1400         2012-01-01
4500         3000         2013-01-01
9000         5000         2014-01-01

The code I used to create the date format is data$year<-lubridate::ymd(data$year, truncated = 2L) because the dates originally appeared just as years (ex. 2011, 2012, 2013, etc.).

To create my graph, I used:

data %>% 
  filter(company=="minsur") %>% 
  ggplot(aes(x=year))+
  geom_line(aes(y=money1, color="Money1"))+
  geom_line(aes(y=money2, color="Money2")) 

I want to add a red dot to the graph during the year 2012 (where it falls on the y axis is unimportant for now).

I've tried:

data %>% 
  filter(company=="minsur") %>% 
  ggplot(aes(x=year))+
  geom_line(aes(y=money1, color="Money1"))+
  geom_line(aes(y=money2, color="Money2")) 
  geom_point(aes(x="2012-01-01", y=3000),size = 1,colour = "Red")

But I get this error: Error: Discrete value supplied to continuous scale

I've tried many other techniques and have yet to get it to run without an error of some kind. Does anyone know how to format the geom_point to work with my Date x axis?

When you have "2012-01-1", R considers this character data. You need to make it a date.

geom_point(aes(x = as.Date("2012-01-01"), y=3000), size = 1, colour = "Red")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM