这是我的密码。只是一个简单的历史记录。但我想做的是定制悬停文本,以便当我悬停时,它将显示包括在该直方图栏中的所有物种。你能帮我吗?
iris %>%
plot_ly(x=~Sepal.Length, color=~Sepal.Width, text=~Species) %>%
add_histogram()这是输出。但当我悬停时,文本似乎只显示了表中的第一个物种。赫斯特
发布于 2020-06-24 21:01:25
我不确定这是否可能。可能你对我的要求太高了。在尝试了一些选项之后,如果您希望在工具提示中显示不同的Species,我认为有两种方法:
第一个选项是使用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中的统计层来完成所有的计算。据我所知,不可能那么轻易地使用“纯”手法。
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()https://stackoverflow.com/questions/62558271
复制相似问题