如何在 r-plotly 中动态添加注释到折线图的峰值?
How to dynamically add annotation to peak of line graph in r-plotly?
我正在尝试重现 this page 中显示的代码,特别是名为 "Mix data manipulation and visualization verbs."
的代码
我实际上只是复制粘贴了代码并做了一些小改动,使其成为 运行(plot_ly
现在要求使用“~”等引用列名)。但是,我的图表看起来非常不同:
我有什么
我查看了 plot_ly 中的注释,但似乎该点需要硬编码,而不是像作者那样能够自动使用 filter
。 (除非我误会了。)这就是我正在使用的:
p4 <- plot_ly(economics, x = economics$date, y = economics$uempmed)
p4 %>%
add_trace(y = fitted(loess(economics$uempmed ~ as.numeric(economics$date)))) %>%
add_lines(x = economics$date, y = economics$uempmed) %>%
layout(title = "Median duration of unemployment (in weeks)",
showlegend = FALSE) %>%
dplyr::filter(economics$uempmed == max(economics$uempmed)) %>%
layout(annotations = list(x = economics$date, y = economics$uempmed, text = "Peak", showarrow = T))
我希望它看起来像网站上的那样(如下),但注释文本似乎只是在整行中被垃圾邮件发送,而不是只停留在最大值处:
它应该是什么样子
谁能告诉我哪里做错了?
为什么不先预计算峰值再入链
peak <- dplyr::filter(economics, uempmed == max(uempmed))
p4 %>%
add_trace(y = fitted(loess(economics$uempmed ~ as.numeric(economics$date)))) %>%
add_lines(x = economics$date, y = economics$uempmed) %>%
layout(title = "Median duration of unemployment (in weeks)",
showlegend = FALSE) %>%
layout(annotations = list(x = peak$date, y = peak$uempmed, text = "Peak", showarrow = T))
我正在尝试重现 this page 中显示的代码,特别是名为 "Mix data manipulation and visualization verbs."
的代码我实际上只是复制粘贴了代码并做了一些小改动,使其成为 运行(plot_ly
现在要求使用“~”等引用列名)。但是,我的图表看起来非常不同:
我有什么
我查看了 plot_ly 中的注释,但似乎该点需要硬编码,而不是像作者那样能够自动使用 filter
。 (除非我误会了。)这就是我正在使用的:
p4 <- plot_ly(economics, x = economics$date, y = economics$uempmed)
p4 %>%
add_trace(y = fitted(loess(economics$uempmed ~ as.numeric(economics$date)))) %>%
add_lines(x = economics$date, y = economics$uempmed) %>%
layout(title = "Median duration of unemployment (in weeks)",
showlegend = FALSE) %>%
dplyr::filter(economics$uempmed == max(economics$uempmed)) %>%
layout(annotations = list(x = economics$date, y = economics$uempmed, text = "Peak", showarrow = T))
我希望它看起来像网站上的那样(如下),但注释文本似乎只是在整行中被垃圾邮件发送,而不是只停留在最大值处:
它应该是什么样子
谁能告诉我哪里做错了?
为什么不先预计算峰值再入链
peak <- dplyr::filter(economics, uempmed == max(uempmed))
p4 %>%
add_trace(y = fitted(loess(economics$uempmed ~ as.numeric(economics$date)))) %>%
add_lines(x = economics$date, y = economics$uempmed) %>%
layout(title = "Median duration of unemployment (in weeks)",
showlegend = FALSE) %>%
layout(annotations = list(x = peak$date, y = peak$uempmed, text = "Peak", showarrow = T))