問題
我正在分析瑞士的雪崩事故,并使用 和 創建了一個ggplotly地圖geom_sf。我現在想調整圖中點的 hoverinfo,以便它還顯示包含在資料框中但不包含在圖中的變數year和placeaes()。
資料
head(df)
LV03_E LV03_N deaths caughts year canton place
1 602380 131230 2 2 1995 VS Chetseron / Vallon de l`Ertentse
2 586070 104160 1 1 1995 VS Verbier / Les Ruinettes
3 731720 155110 1 4 1996 GR Chilchalphorn
4 575300 141010 1 2 1996 VD La L\xe9cherette
5 661640 202180 1 4 1996 OW Pilatus / Matthorn / Ruessiflue
6 820490 206020 1 1 1996 GR Alp Trida / Greitspitz
陰謀
ggplotly(
ggplot()
geom_sf(data = swiss_cantons, fill = NA)
geom_point(data = df_avalanches_places,
mapping = aes(x = LV03_E, y=LV03_N, size = deaths), colour = "lightblue", alpha = 0.7)
theme_minimal())

預期結果
hoverinfo 應采用以下形式:
地點
年
死亡
人數
我試過的
我試圖通過在中包含所需的變數aes()然后在中使用tooltip來解決問題ggplotly(),但我收到一條錯誤訊息。
ggplotly(
ggplot()
geom_sf(data = swiss_cantons, fill = NA)
geom_point(data = df_avalanches_places,
mapping = aes(x = LV03_E, y = LV03_N, size = deaths, place = place, year = year, caught = caughts), colour = "lightblue", alpha = 0.7)
theme_minimal(), tooltip = c('year', 'place', 'size', 'caught'))
Error in gsub("\n", br(), a, fixed = TRUE) :
input string 4 is invalid in this locale
In addition: Warning message:
Ignoring unknown aesthetics: place, year, caught
如何正確調整 hoverinfo?
uj5u.com熱心網友回復:
您可以創建一個名為 tooltip 的新列來撰寫要顯示的文本,然后將此列映射到 aestetic:
library(ggplot2)
library(plotly)
plt <-
iris %>%
mutate(tooltip = paste(Species, "Petal Length:", Petal.Length, sep = "\n")) %>%
ggplot(aes(Sepal.Length, Sepal.Width, tooltip = tooltip))
geom_point()
ggplotly(plt, tooltip = "tooltip")

我認為這不是空間地圖的問題,所以我創建了這個更最小的可重現示例。
uj5u.com熱心網友回復:
默認情況下,plolty 工具提示對應于繪圖的實際美學。考慮使用要顯示的元素創建一個新變數。
library(dplyr)
library(ggplot2)
library(plotly)
library(glue)
plot <- mtcars %>%
mutate(
model = rownames(.),
label = glue::glue('{model} \nMPG:{mpg} \nWT: {wt}' )
) %>%
ggplot(aes(x = wt, y = mpg, text = label))
geom_point()
ggplotly(plot, tooltip = 'text')

轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/428868.html
