如何将手绘红色圆圈添加到 ggplot2 图形中?

How can I add freehand red circles to a ggplot2 graph?

去年我发帖 an analysis of user activity to Meta Stack Overflow, including a series of ggplot2 graphs. However, Wooble 指出了我情节的一个致命缺陷,这让我非常羞愧:

写意红圈are of course necessary in any plot on Meta Stack Overflow, but to my dismay I could not find a way to add them to a ggplot2 graph. I know how to add a circle,但这样的人为构造没有个性,永远不会通过Meta。

作为一个可重现的例子,考虑我自己的回答 activity 随着时间的推移,使用 stackr 包创建的这个图:

# devtools::install_github("dgrtwo/stackr")
library(ggplot2)
library(dplyr)
library(lubridate)
library(stackr)

answers <- stack_users(712603, "answers", num_pages = 10, pagesize = 100)
answers_per_month <- answers %>%
    mutate(month = round_date(creation_date, "month")) %>%
    count(month)

ggplot(answers_per_month, aes(month, n)) + geom_line()

这个剧情信息量够大,但是没有灵魂。怎么给它加上手绘红圈?

您可以使用我的 ggfreehand 包,它提供了 ggplot2 中不小心遗漏的 geom_freehand 层。

例如,如果您想圈出上图中最活跃的前两个月份,您可以按照以下代码:

top_2_months <- answers_per_month %>% top_n(2)

library(ggfreehand)
ggplot(answers_per_month, aes(month, n)) + geom_line() +
    geom_freehand(data = top_2_months)

就这样,情节现在值得发布在 Meta Stack Overflow 上。

geom_freehand 图层采用其他选项来自定义圆,包括 radiusnoisiness。你也可以让圆圈不是红色的,就好像那是你永远想做的事情一样。

p <- ggplot(answers_per_month, aes(month, n)) + geom_line()

p + geom_freehand(data = top_2, radius = .5)
p + geom_freehand(data = top_2, noisiness = 10)
p + geom_freehand(data = top_2, noisiness = 1)
p + geom_freehand(data = top_2, color = "blue")