I have this issue where I have to add a "target" point to an existing plot, based on a value in the data.
For example, in the reprex - to make a point at (2010, 605). (target year, 110% of 2008 profit)
I know I can calculate before plotting ... but is there a way using that .data pronoun to get the profit for 2008 within the ggplot?
Reprex:
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"])
You can use :
library(ggplot2)
ggplot(sales) + aes(x = year, y = profit) +
geom_line() +
geom_point(aes(x = 2010, y = .data[['profit']][.data[["year"]] == 2008]))