简体   繁体   English

如何在r-plotly中向折线图的峰值动态添加注释?

[英]How to dynamically add annotation to peak of line graph in r-plotly?

I am trying to reproduce the code shown in this page , specifically the one named "Mix data manipulation and visualization verbs."我正在尝试重现此页面中显示的代码,特别是名为“混合数据操作和可视化动词”的代码

I literally just copy-pasted the code and made a few minor changes to get it to run ( plot_ly now requires column names to be referenced with a "~", etc).我实际上只是复制粘贴了代码并进行了一些小的更改以使其运行( plot_ly现在要求使用“~”等引用列名)。 However, my graph looks very different:但是,我的图表看起来非常不同:

What I have我拥有的我拥有的

I looked into annotations in plot_ly but it seems like the point needs to be hard-coded in, instead of being able to use filter automatically like the author did.我查看了 plot_ly 中的注释,但似乎需要对这一点进行硬编码,而不是像作者那样自动使用filter (Unless I am misunderstanding.) This is what I'm using: (除非我误解了。)这就是我正在使用的:

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))

I expected it to look like it does on the website (below), but it seems like the annotation text is just being spammed across the whole line instead of just staying at the max:我希望它看起来像在网站上(如下),但似乎注释文本只是在整行中被垃圾邮件而不是仅仅停留在最大值:

What it should look like它应该是什么样子

它应该是什么样子

Can someone tell me what I'm doing wrong?有人能告诉我我做错了什么吗?

Why not pre-calcaualte the peak first before putting it in the chain为什么不在将其放入链之前先预先计算峰值

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM