繁体   English   中英

R plotly 直方图 hover 文本

[英]R plotly histogram hover text

这是我的代码。 只是一个简单的直方图。 但我想做的是自定义 hover 文本,这样当我 hover 时,它将显示该直方图栏中包含的所有物种。 你能帮助我吗?

iris %>% 
  plot_ly(x=~Sepal.Length, color=~Sepal.Width, text=~Species) %>% 
  add_histogram()

这是 output。 但是当我 hover 似乎文本只显示表中的第一个物种。 plotly_hist

我不确定这是否可能。 可能你对 plotly 的要求太高了。 在尝试了一些选项后,我认为如果您希望在工具提示中显示不同的Species ,有两种方法可以 go:

第一个选项是使用hovermode = "unified"的堆叠直方图,如下所示:

library(plotly)

fig <- plot_ly()

fig <- fig %>% add_trace(data = filter(iris, Species == "setosa"), 
                         x = ~Sepal.Length,
                         color = ~Species,
                         text = ~Species,
                         type='histogram',
                         bingroup=1, showlegend = FALSE)

fig <- fig %>% add_trace(data = filter(iris, Species == "versicolor"),
                         x = ~Sepal.Length,
                         color = ~Species,
                         text = ~Species,
                         type='histogram',
                         bingroup=1, showlegend = FALSE)

fig <- fig %>% add_trace(data = filter(iris, Species == "virginica"),
                         x = ~Sepal.Length,
                         color = ~Species,
                         text = ~Species,
                         type='histogram',
                         bingroup=1, showlegend = FALSE)

fig <- fig %>% layout(
  hovermode="unified",
  barmode="stack",
  bargap=0.1)

fig

第二种选择是自己进行计算,即分箱和汇总并制作计数条形图。

iris %>% 
  mutate(Sepal.Length.Cut = cut(Sepal.Length, breaks = seq(4, 8, .5), right = FALSE)) %>% 
  group_by(Sepal.Length.Cut, Species) %>% 
  summarise(n = n(), Sepal.Width = sum(Sepal.Width)) %>% 
  tidyr::unite("text", Species, n, sep = ": ", remove = FALSE) %>%
  summarise(n = sum(n), Sepal.Width = sum(Sepal.Width) / n, text = paste(unique(text), collapse = "\n")) %>% 
  plot_ly(x = ~Sepal.Length.Cut, y = ~n, text = ~text) %>% 
  add_bars(marker = list(colorscale = "Rainbow"), hovertemplate = "%{y}<br>%{text}")

编辑第三个选项是使用ggplotly() 这样,添加注释以显示每个 bin 的总数是一项简单的任务。 这样我们就可以利用 ggplot2 中的统计层来完成所有的计算。 据我所知,使用“纯”plotly 无法轻易做到这一点。

library(plotly)

ggplot(iris, aes(Sepal.Length, fill = Species)) +
  stat_bin(breaks = seq(4, 8, .5), closed = "left") +
  stat_bin(breaks = seq(4, 8, .5), closed = "left", geom = "text", mapping = aes(Sepal.Length, label = ..count..), inherit.aes = FALSE, vjust = -.5) +
  theme_light()

ggplotly()

暂无
暂无

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

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