【问题标题】:Adding a point based on data to ggplot将基于数据的点添加到ggplot
【发布时间】:2021-05-10 10:56:12
【问题描述】:

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

例如,在 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"])

【问题讨论】:

    标签: r ggplot2 tidyeval


    【解决方案1】:

    你可以使用:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-11
      • 1970-01-01
      • 2020-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      • 2023-03-16
      相关资源
      最近更新 更多