使用ggplot2在R中编辑Plotly地图工具提示中的标签

10
我知道这个问题已经被问了很多次,但我认为自那些问题被提出以来,plotly的一些基本语法已经发生了变化。使用ggplotly()创建区域填充地图会给出默认的工具提示,包括经度、纬度、组和我的美学之一的变量。我知道工具提示只显示美学中的内容。我想要做的就是自定义工具提示,使其显示数据集中的一些变量(包括那些未映射到美学的变量),而不显示其他变量(如坐标)。下面是一个可复制的示例以及我迄今为止尝试过的内容。我按照其他问题的回答所给的建议去尝试,但没有成功。
#Load dependencies
library(rgeos)
library(stringr)
library(rgdal)
library(maptools)
library(ggplot2)
library(plotly)

#Function to read shapefile from website
dlshape=function(shploc, shpfile) {
  temp=tempfile()
  download.file(shploc, temp)
  unzip(temp)
  shp.data <- sapply(".", function(f) {
    fp <- file.path(temp, f)
    return(readOGR(".",shpfile))
  })
}

austria <- dlshape(shploc="http://biogeo.ucdavis.edu/data/gadm2.8/shp/AUT_adm_shp.zip", 
                   "AUT_adm1")[[1]]
#Create random data to add as variables
austria@data$example1<-sample(seq(from = 1, to = 100, by = 1), size = 11, replace = TRUE)
austria@data$example2<-sample(seq(from = 1, to = 100, by = 1), size = 11, replace = TRUE)
austria@data$example3<-sample(seq(from = 1, to = 100, by = 1), size = 11, replace = TRUE)

#Fortify shapefile to use w/ ggplot
austria.ft <- fortify(austria, region="ID_1")
data<-merge(austria.ft, austria, region="id", by.x = "id", by.y = "ID_1")

#Save as ggplot object    
gg<-ggplot(data, aes(x = long, y = lat, fill = example1, group = group)) + 
  geom_polygon() + geom_path(color="black",linetype=1) + 
  coord_equal() +
  scale_fill_gradient(low = "lightgrey", high = "darkred", name='Index') +xlab("")+ylab("") + 
  theme(axis.text = element_blank(), 
        axis.title = element_blank(), 
        axis.ticks = element_blank()) + 
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), 
        panel.background = element_blank(), axis.line = element_line(colour = "black")) + 
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), 
        panel.background = element_blank(), axis.line = element_line(colour = "black"))

#Plot using ggplotly
ggplotly(gg)

从这里开始,我尝试了两种不同的方法。其中最成功的一种方法在某种程度上帮助我实现了目标。我可以向工具提示添加新变量,但我无法做到以下两点:1)我无法摆脱默认显示的其他变量(来自美学),2)我无法将变量重命名为数据集中的列名称之外的其他名称(例如,我想将“example3”标记为“Example III”)。以下是该方法:

#Save as a new ggplot object except this time add ``label = example3`` to the aesthetics
 gg2<-ggplot(data, aes(x = long, y = lat, fill = example1, group = group, label = example3)) + 
  geom_polygon() + geom_path(color="black",linetype=1) + 
  coord_equal() +
  scale_fill_gradient(low = "lightgrey", high = "darkred", name='Index') +xlab("")+ylab("") + 
  theme(axis.text = element_blank(), 
        axis.title = element_blank(), 
        axis.ticks = element_blank()) + 
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), 
        panel.background = element_blank(), axis.line = element_line(colour = "black")) + 
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), 
        panel.background = element_blank(), axis.line = element_line(colour = "black"))

#Save as plotly object then plot
gg2 <- plotly_build(gg2)
gg2

我也尝试添加了以下内容,但没有任何效果:
gg2$data[[1]]$text <- paste("Example I:", data$example1, "<br>",
                           "Example II:", data$example2, "<br>",
                           "Example III:", data$example3)

任何帮助都非常感激!
更新:我通过从Github安装而不是CRAN来更新了plotly。使用这个更新的版本(4.0.0),我已经完成了一部分。
gg2$x$data[[2]]$text <- paste("Example I:", data$example1, "<br>",
                             "Example II:", data$example2, "<br>",
                             "Example III:", data$example3)
gg2

现在发生的事情让我感到困惑。这会添加一个与之前不同的附加工具提示。这个新的工具提示正是我想要的,但它们两个都出现了 - 不是同时出现,而是当我移动鼠标时。请参见下面的两个截图:

This is the old tooltip from before that still lingers This is the new one and the only one I want to keep

请注意,这些工具提示来自同一单元(Tirol)。这可能是软件包中的错误吗?当显示其他图表(如时间序列)而不是地图时,不会出现此问题。还要注意,我分配了标签“示例I”(或II或III),但这不会显示在我添加的新工具提示上。
更新#2:我发现旧的工具提示(显示长和宽)仅在悬停在边框上时才出现,因此我删除了 geom_path(color =“black”,linetype = 1)命令(以删除边框),现在我已成功解决了这个问题。但是,我仍然无法修改工具提示中显示的标签。
更新#3:我发现如何编辑标签,但仅适用于一个变量。这太疯狂了!以下是我的工作流程:
 #Load dependencies
    library(rgeos)
    library(stringr)
    library(rgdal)
    library(maptools)
    library(ggplot2)
    library(plotly)

    #Function to read shapefile from website
    dlshape=function(shploc, shpfile) {
      temp=tempfile()
      download.file(shploc, temp)
      unzip(temp)
      shp.data <- sapply(".", function(f) {
        fp <- file.path(temp, f)
        return(readOGR(".",shpfile))
      })
    }

    austria <- dlshape(shploc="http://biogeo.ucdavis.edu/data/gadm2.8/shp/AUT_adm_shp.zip", 
                       "AUT_adm1")[[1]]
    #Create random data to add as variables
    austria@data$example1<-sample(seq(from = 1, to = 100, by = 1), size = 11, replace = TRUE)
    austria@data$example2<-sample(seq(from = 1, to = 100, by = 1), size = 11, replace = TRUE)
    austria@data$example3<-sample(seq(from = 1, to = 100, by = 1), size = 11, replace = TRUE)

    #Fortify shapefile to use w/ ggplot
    austria.ft <- fortify(austria, region="ID_1")
    data<-merge(austria.ft, austria, region="id", by.x = "id", by.y = "ID_1")

    #Save as ggplot object    
    gg<-ggplot(data, aes(x = long, y = lat, fill = example1, group = group, text = paste("Province:", NAME_1))) + 
      geom_polygon(color="black", size=0.2) + 
      coord_equal() +
      scale_fill_gradient(low = "lightgrey", high = "darkred", name='Index') +xlab("")+ylab("") + 
      theme(axis.text = element_blank(), 
            axis.title = element_blank(), 
            axis.ticks = element_blank()) + 
      theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), 
            panel.background = element_blank(), axis.line = element_line(colour = "black")) + 
      theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), 
            panel.background = element_blank(), axis.line = element_line(colour = "black"))


gg <- plotly_build(gg)
gg

这将产生以下绘图:

enter image description here

请注意,“Province”现在是大写的(之前不是)。诀窍是将text = paste("Province:", NAME_1)添加到美学中。然而,当我尝试使用text2=paste("Example III:", example1)添加其他标签更改时,会出现以下情况:

enter image description here

请注意,它无法像呈现text1一样呈现text2。因此,我尝试添加一个没有text2的副本,如下所示:text=paste("Example III:", example1) - 它会产生以下奇怪的结果:

enter image description here

我开始认为在plotly的ggplot转换中切换“legend”选项这么简单的事情是不可能的。 更新#4:所以我决定用另一种方式来解决这个问题。相反,我决定改变变量名本身。我本来会从一开始就这样做的,只是我不确定ggplot2是否接受带有空格的变量 - 我找到了`variable`可以工作的方法。所以我继续重命名变量。它有效 - 但是有一个问题,文本周围出现了引号。现在我需要一种方法来摆脱这些!!!任何人有想法吗?谢谢!这是我所说的引用文字的图像:

enter image description here


1
我想知道你是否遇到过这样的问题,即尝试使用注释标记点,然后为工具提示使用不同的变量。例如,按名称标记这些区域,然后在工具提示中显示统计信息。我一直在尝试做这个,但是 ggplotly 总是将标签作为工具提示文本,即使我明确传递了文本和标签。有什么想法可以帮助吗? - jtanman
1个回答

16

我对plotly也很陌生,但是在使用ggplotly()时遇到了和你类似的问题,我的问题是关于ggplot2气泡图。最终我找到了一个可行的解决方案,希望它对你也有所帮助,尽管我没有在等值线地图上试过。

你的第一个问题是如何自定义工具提示,以便显示数据集中的某些变量(包括未映射到美学上的变量)。
在你的UPDATE#3中,你将 text = paste("Province:", NAME_1) 加入到 aes 中。如果你想添加第二行自定义变量或文本,请将其添加到括号中:text = paste("Province:", NAME_1, "Example III:", example1) 如果你想在两者之间添加换行,则在想要添加换行的位置添加<br>,例如:text = paste("Province:", NAME_1, "<br>", "Example III:", example1)

你的第二个问题是如何自定义工具提示,以便不显示其他(默认)变量(例如坐标),而只显示你指定的内容。
我在ggplotly()函数中发现了一个非常简单的补充方法,可以解决这个问题:ggplotly(gg, tooltip = c("text"))在我的情况下,这将删除工具提示中显示的所有默认变量,并仅显示使用text自定义指定的变量。你可以通过执行ggplotly(gg, tooltip = c("text","x"))来添加其他变量。在工具提示中显示的变量顺序将与tooltip参数中指定的顺序相同。我在这里找到了文档:https://github.com/ropensci/plotly/blob/master/R/ggplotly.R

这个解决方案(原则上)适用于我的R 3.1.1和plotly 3.4.13版本。


1
你知道是否有可能摆脱当悬停在其他 aes 映射上时出现的工具提示,例如此问题的边框?例如,在我的 ggplot 中,我在数据点旁边有标签,并且像您推荐的示例一样构建了我的文本映射:ggplot(randomData, aes(x, y, label=ip_country, text=paste('Country:', ip_country, '<br>', 'x:', x)) + geom_point() + geom_text(aes(x=x-1))然后当我使用 ggplotly 转换时,文本标签也会有一个悬停工具提示,只显示文本标签,而实际数据点将显示正确的悬停工具提示。 - jtanman
1
我有同样的问题,即使使用c("text")我也无法摆脱工具提示中的默认轴信息,我可以看到我的新文本,但仍然看到默认文本。你有任何想法为什么会这样吗? - InesGuardans

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接