将基于数据的点添加到ggplot

Adding a point based on data to ggplot

我遇到这个问题,我必须根据数据中的值向现有绘图添加“目标”点。

例如,在 reprex 中 - 在 (2010, 605) 处创建一个点。 (目标年份,2008年利润的110%)

我知道我可以在绘图之前进行计算...但是有没有办法使用该 .data 代词在 ggplot 中获得 2008 年的利润?

代表:

library(ggplot2)

sales <- data.frame(
  year = c(2005, 2006, 2007, 2008),
  profit = c(340, 500, 600, 550)
)

sales %>% 
  ggplot() +
  aes(x = year, y = profit) +
  geom_line() +
# throws error: Error: Discrete value supplied to continuous scale
  geom_point(aes(x = 2010, y = .data[["year"]] == 2008))


# calculate before plot
pull(sales[sales[["year"]] == 2008, ]["profit"])

您可以使用:

library(ggplot2)

ggplot(sales) + aes(x = year, y = profit) +
  geom_line() + 
  geom_point(aes(x = 2010, y = .data[['profit']][.data[["year"]] == 2008]))