简体   繁体   English

当x轴为日期格式时,在ggplot中添加点到折线图

[英]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.我使用 ggplot 构建了一个折线图,显示了公司多年来两种不同类型的货币贡献的变化。 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.由于我的 x 轴是日期格式,我正在努力使用 geom_point 添加点。

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.).我用来创建日期格式的代码是data$year<-lubridate::ymd(data$year, truncated = 2L)因为日期最初显示为年份(例如 2011、2012、2013 等)。

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).我想在 2012 年期间在图表中添加一个红点(它落在 y 轴上的位置现在并不重要)。

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?有谁知道如何格式化 geom_point 以使用我的日期 x 轴?

When you have "2012-01-1", R considers this character data.当您有“2012-01-1”时,R 会考虑此字符数据。 You need to make it a date.你需要让它成为一个约会。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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