首页 > 解决方案 > 如何格式化 R plotly 工具提示中的变量名称?

问题描述

我一直在尝试制作一张美国地图,其中包含枪击事件的叠加散点图,每个点的 hoverinfo 标签中都有死亡人数和受伤人数。但是,标签弹出为“num_killed”,我想将其格式化为“Number Killed:”。到目前为止,我已经尝试在 ggplot 部分中标记变量,但无济于事。有什么方法可以更改变量名称在工具提示中的打印方式?

这是我的代码:

library(plotly)
library(dplyr)
library(ggplot2)

us <- map_data("state")
library(maps)

g <- ggplot() +
  geom_polygon(data = us, aes(x=long, y = lat, group = group), fill="grey", alpha=0.3) +
  geom_point(data=shootings, aes(x=lng, y=lat, size = num_killed, color = num_injured)) +
  labs(color = "Number Injured", size = "Number Killed", num_killed = "Number Killed", num_injured = "Number Injured")
plot <- ggplotly(g)

结果如下: 显示工具提示的图像

附加的数据集是该数据库的处理后的 csv:http ://www.gunviolencearchive.org/reports/mass-shooting?page=1 (作为数据框处理)。

标签: rggplot2plotlyr-plotlyggplotly

解决方案


这应该给你你想要的:

g <- ggplot() +
  geom_polygon(data = us, aes(x=long, y = lat, group = group), fill="grey", alpha=0.3) +
  geom_point(data=shootings, aes(x=lng, y=lat, size = num_killed, color = num_injured,
                                 text = paste('lng: ', lng,
                                              '<br>lat:', lat, 
                                              '<br>Number Killed:', num_killed,
                                              '<br>num_injured:', num_injured)))

ggplotly(g, tooltip = "text")

推荐阅读