简体   繁体   English

使用r中的ggplot2在工具提示中编辑用于绘制地图的标签

[英]Edit labels in tooltip for plotly maps using ggplot2 in r

I know this question has been asked a number of times but I think some of the underlying syntax for plotly has changed since those questions have been asked. 我知道这个问题已被多次询问,但我认为,自从提出这些问题以来,情节的一些基本语法已经改变了。 Using ggplotly() to create a choropleth map gives the default tooltip of long, lat, group, and one of my variables from my aesthetics. 使用ggplotly()创建一个等值区域贴图,从我的美学中提供了long,lat,group和我的一个变量的默认工具提示。 I understand that tooltip maps only whats in the aesthetics. 我知道工具提示只映射了美学中的什么。 All I want to do is to customize the tooltip so it displays some of the variables in my dataset (including those not mapped to aesthetics) and not others (such as the coordinates). 我想要做的就是自定义工具提示,以便在我的数据集中显示一些变量(包括那些未映射到美学的变量)而不显示其他变量(例如坐标)。 Below is a reproducible example and what I've tried so far. 下面是一个可重复的例子,到目前为止我尝试过的。 I followed the advice given in response to other questions to no avail. 我跟着回答其他问题的建议无济于事。

#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)

From here I've tried two different approaches. 从这里开始,我尝试了两种不同的方法。 The most successful one of the approaches gets me there in part. 最成功的方法之一就是让我在那里。 I can add new variables to to the tooltip but I cannot do two things: 1) I cannot get rid of other variables already displayed by default (from the aesthetics) and 2) I cannot rename the variables something other than their column name from the dataset (for example I would like to label "example3 as "Example III"). Here is that approach: 我可以将新变量添加到工具提示中但我不能做两件事:1)我无法摆脱默认情况下已经显示的其他变量(来自美学)和2)我不能将变量重命名为除了列名以外的变量数据集(例如,我想将“example3”标记为“示例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

I also tried adding the following but it did nothing: 我也尝试添加以下内容但它没有做任何事情:

gg2$data[[1]]$text <- paste("Example I:", data$example1, "<br>",
                           "Example II:", data$example2, "<br>",
                           "Example III:", data$example3)

Any help is much appreciated! 任何帮助深表感谢!

UPDATE: I updated plotly by installing from github instead of CRAN. 更新:我更新plotly从github上,而不是安装CRAN。 Using this updated version (4.0.0) I've made it apart of the way there. 使用这个更新版本(4.0.0)我已经把它分开了。

gg2$x$data[[2]]$text <- paste("Example I:", data$example1, "<br>",
                             "Example II:", data$example2, "<br>",
                             "Example III:", data$example3)
gg2

What happens now simply baffles me. 现在发生的事情简直让我感到困惑。 This adds an additional tooltip separate from the previous one. 这会增加一个与前一个工具提示分开的额外工具提示。 This new tooltip is exactly what I want however both of them appear -not at once but if I move my mouse around. 这个新的工具提示正是我想要的,但是它们都出现了 - 不是一次但是如果我移动我的鼠标。 See the two screenshots below: 请参阅以下两个屏幕截图:

这是之前仍然存在的旧工具提示 这是新的,也是我唯一要保留的

Notice those tooltips are from the same unit (Tirol). 请注意,这些工具提示来自同一个单元(蒂罗尔)。 Could this be a bug in the package? 这可能是包中的错误吗? This does not occur when display other graphs such as a time-series instead of a map. 显示其他图形(例如时间序列而不是地图)时不会发生这种情况。 Also note, that I assigned the label "Example I" (or II or III) and this does not show on the new tooltip I added. 另请注意,我指定了标签“示例I”(或II或III),但这并未在我添加的新工具提示中显示。

UPDATE #2: I figured out that the old tooltip (with long and lat shown) only appears when hovering over the borders so I got rid of the geom_path(color="black",linetype=1) command (as to remove the borders) and now I've managed to successfully solve that problem. 更新#2:我发现旧的工具提示(显示长和lat)仅在悬停在边框上时出现,因此我摆脱了geom_path(color="black",linetype=1)命令(以删除边框) )现在我成功解决了这个问题。 However, I'm still unable to modify the labels that appear in the tooltip. 但是,我仍然无法修改工具提示中显示的标签。

UPDATE #3: I figured out how to edit the labels but FOR ONLY ONE VARIABLE. 更新#3:我想出了如何编辑标签,但只有一个变量。 Which is nuts! 哪个是坚果! Here's my workflow from start to finish: 这是我从开始到结束的工作流程:

 #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

That produces the following plot: 这产生了以下情节:

在此输入图像描述

Notice that "Province" is now capitalized (it was not before). 请注意,“省”现在已大写(之前不是)。 The trick was adding text = paste("Province:", NAME_1) to the aesthetics. 诀窍是将text = paste("Province:", NAME_1)到美学中。 HOWEVER, when I tried to add additional label changes using text2=paste("Example III:", example1) , the following occurs: 但是,当我尝试使用text2=paste("Example III:", example1)添加其他标签更改时,会发生以下情况:

在此输入图像描述

Notice that it cannot render text2 the same way it renders text1. 请注意,它无法以与呈现text1相同的方式呈现text2。 So instead I simply try adding a duplicate without the text2 like in the following: text=paste("Example III:", example1) -which produces the following odd result: 所以我只是尝试添加没有text2的副本,如下所示: text=paste("Example III:", example1) - 它产生以下奇怪的结果:

在此输入图像描述

I'm beginning to think something as simple as toggling "legend" options in plotly's ggplot conversion is impossible. 我开始认为在plotly的ggplot转换中切换“图例”选项这么简单是不可能的。 UPDATE #4: So I decided to approach this another way. 更新#4:所以我决定采用另一种方式。 Instead, I decided to change the variable names themselves. 相反,我决定自己更改变量名称。 I would have done this from the start, except I wasn't sure if/how ggplot2 accepts variables with spaces -i figured out `variable` that can work. 我会从一开始就做到这一点,除了我不确定ggplot2是否/如何接受带空格的变量-i想出可以工作的`variable` So I went ahead and relabeled the variables. 所以我继续并重新标记变量。 It works -KINDA. 它有效--KINDA。 The problem is the text appears with the quotations marks around them. 问题是文本出现时带有引号。 Now I need a way to get rid of these!!! 现在我需要一种摆脱这些的方法! Any ideas anyone? 任何人的想法? Thanks! 谢谢! Here is an image of what I mean by quotations in the text: 这是我在文中引用的意思的图像:

在此输入图像描述

I am new to plotly too but have come across a similar problem for my ggplot2 bubble plots when using ggplotly() . 我是新手,但在使用ggplotly()时,我的ggplot2气泡图遇到了类似的问题。 I have finally found a solution that works for me and thought it might help you, too, although I haven't tried it for choropleth maps. 我终于找到了一个对我有用的解决方案,并认为它也可能对你有所帮助,虽然我还没有尝试过用于等值线图。

Your first question was to customize the tooltip so it displays some of the variables in the dataset (including those not mapped to aesthetics). 您的第一个问题是自定义工具提示,以便显示数据集中的一些变量(包括那些未映射到美学的变量)。
In your UPDATE#3 you introduce: text = paste("Province:", NAME_1) into your aes. 在您的更新#3中,您将: text = paste("Province:", NAME_1)引入您的aes。 If you want to add a second line of custom variables or text, just keep adding it into the brackets: text = paste("Province:", NAME_1, "Example III:", example1) To add a line break between both add <br> in the spot where you want the break to be, like: text = paste("Province:", NAME_1, "<br>", "Example III:", example1) 如果要添加第二行自定义变量或文本,只需将其添加到括号中: text = paste("Province:", NAME_1, "Example III:", example1)在两者之间添加换行符<br>在您想要休息的地方,例如: text = paste("Province:", NAME_1, "<br>", "Example III:", example1)

Your second question was to customize the tooltip so it does NOT display other (default) variables (that are mapped to aesthetics, such as the coordinates). 您的第二个问题是自定义工具提示,因此它不显示其他(默认)变量(映射到美学,例如坐标)。
I found this very easy addition to the ggplotly() function that did the trick for me: ggplotly(gg, tooltip = c("text")) In my case, this removed ALL default variables that are shown in the tooltip and only showed those that are custom specified with text above. 我发现ggplotly()函数很容易添加到我这里的技巧: ggplotly(gg, tooltip = c("text"))在我的例子中,这删除了工具提示中显示的所有默认变量并且只显示那些用上面的text指定的自定义。 You can add other variables back in by doing ggplotly(gg, tooltip = c("text","x")) The order of the variables shown in the tooltip will be the same as the order specified in the tooltip argument. 您可以通过执行ggplotly(gg, tooltip = c("text","x"))添加其他变量ggplotly(gg, tooltip = c("text","x"))工具提示中显示的变量的顺序将与tooltip参数中指定的顺序相同。 I found this documented here: https://github.com/ropensci/plotly/blob/master/R/ggplotly.R 我在这里记录了这个: https//github.com/ropensci/plotly/blob/master/R/ggplotly.R

This solution worked (in principle) for me using R 3.1.1 and plotly 3.4.13 这个解决方案(原则上)使用R 3.1.1和图3.4.13

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

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