使用r中的ggplot2编辑工具提示中的标签以绘制阴谋地图 [英] Edit labels in tooltip for plotly maps using ggplot2 in r

查看:251
本文介绍了使用r中的ggplot2编辑工具提示中的标签以绘制阴谋地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题已经被问过很多次了,但是我认为自从这些问题被问到以后,一些潜在的情节语法已经发生了变化。使用 ggplotly()创建一个等值线图,从我的美学角度给出了默认的long,lat,group和我的一个变量的工具提示。我明白,工具提示只会映射美学中的内容。我想要做的就是自定义工具提示,以便显示我的数据集中的一些变量(包括那些未映射到美学的变量),而不是其他的(如坐标)。下面是一个可重复使用的例子,以及我迄今为止所尝试的内容。

 #负载依赖项
library(rgeos)
library(stringr)
library(rgdal)
library(maptools)
library(ggplot2)
library(plotly)

#Function to从网站阅读shapefile
dlshape =函数(shploc,shpfile){
temp = tempfile()
download.file(shploc,temp)
unzip(temp)
shp.data< - sapply(。,function(f){
fp< - file.path(temp,f)
return(readOGR(。,shpfile))
})
}

奥地利< - dlshape(shploc =http://biogeo.ucdavis.edu/data/gadm2.8/shp/AUT_adm_shp.zip,
AUT_adm1)[[1]]
#创建随机数据作为变量添加
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 = 10 0,by = 1),size = 11,replace = TRUE)

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

#保存为ggplot对象
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(color =black))+
theme(panel.grid.major = element_blank(),panel.grid.minor = element_blank(),
panel.background = element_blank(),axis.line = elem ent_line(color =black))

#Plot using ggplotly
ggplotly(gg)

从这里我尝试了两种不同的方法。最成功的方法之一就是让我在那里。我可以添加新的变量到工具提示,但我不能做两件事:1)我不能摆脱默认已经显示的其他变量(从美学)和2)我不能重命名变量除了它们的列名以外的数据集(例如,我想将example3标记为Example III)。以下是这种方法:

  #Save as一个新的ggplot对象,除了这次添加``label = example3``到美学
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 (),panel.grid.minor = element_blank(),
panel.background = (),panel.grid.minor = element_blank(),
面板。 background = element_blank(),axis.line = element_line(color =black))

#保存为绘图对象然后绘制
gg2 < - plotly_build(gg2)
gg2

我也尝试添加以下内容,但它什么也没做:



$ $ p $ gg2 $ data [[1]] $ text < - paste(Example I:,data $ example1,< br>,
示例二:,data $ example2,< br>,
示例三:,data $ example3)

任何帮助都非常感谢!



更新:我更新了 plotly 通过从github而不是CRAN安装。使用这个更新的版本(4.0.0)我已经做到了这一点。

  gg2 $ x $ data [数据$ example1,< br>,
示例二:,data $ example2,< br>,
例三:,data $ example3)
gg2

现在会发生什么简直让我感到困惑。这增加了一个独立于前一个的附加工具提示。这个新的工具提示正是我想要的,但是他们都出现 - 不是一次,而是如果我移动我的鼠标。看看下面的两张截图:





请注意,这些工具提示来自同一个单位(Tirol)。这可能是包中的错误吗?当显示其他图形(如时间序列)而不是地图时,不会发生这种情况。还要注意,我分配了标签示例I(或II或III),并且这不会显示在我添加的新工具提示中。



更新#2:I发现只有当鼠标悬停在边框上时才会出现旧的工具提示(显示长和经度),所以我摆脱了 geom_path(color =black,linetype = 1)命令(去除边界),现在我已经成功地解决了这个问题。但是,我仍然无法修改出现在工具提示中的标签。



更新#3:我想出了如何编辑标签,但只有一个变量。这是坚果!这里是我从开始到结束的工作流程:

  #Load依赖关系
库(rgeos)
库(stringr )
library(rgdal)
library(maptools)
library(ggplot2)
library(plotly)

#Function从网站$ b读取shapefile $ b 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))
})


奥地利< - dlshape(shploc =http://biogeo.ucdavis.edu/data/gadm2.8/shp/AUT_adm_shp.zip,
AUT_adm1 )[$ 1]
#创建随机数据作为变量添加
austria @ data $ example1 <-sample(seq(from = 1,to = 100,by = 1),size = 11,取样= 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使用w / ggplot
austria.ft < - 强化(austria,region =ID_1)
data< -merge(austria.ft,austria,region =id,by.x =id,by。 y =ID_1)

#保存为ggplot对象
gg <-ggplot(data,aes(x = long,y = lat,fill = example1,group = group,text =粘贴(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(color =black))+
theme(pa nel.grid.major = element_blank(),panel.grid.minor = element_blank(),
panel.background = element_blank(),axis.line = element_line(color =black))


gg< - plotly_build(gg)
gg

产生如下图:



注意省现在已经大写(不是以前)。技巧是在美学中加入 text = paste(Province:,NAME_1)。但是,当我尝试使用 text2 = paste(Example III:,example1)添加其他标签更改时,会发生以下情况:





请注意,它不能呈现text2与呈现text1的相同方式。因此,我只是尝试添加没有text2的副本,如下所示: text = paste(Example III:,example1) - 它会产生以下奇数结果:





我开始认为简单因为在plotly的ggplot转换中切换legend选项是不可能的。
更新#4:所以我决定以另一种方式来处理。相反,我决定自己更改变量名称。我会从一开始就这样做,除非我不确定ggplot2是否接受带空格的变量 - 我想通过`variable` 可以工作。所以我继续为变量重新标记。它的工作原理 - 金达。问题是出现的文字周围带有引号。现在我需要一种方法来摆脱这些!任何想法的人?谢谢!这里是我在文中引用的意思的图片:



<解决方案

我也是新手,但是在使用 ggplotly()。我终于找到了适用于我的解决方案,并认为它也可以帮助你,尽管我还没有尝试过它用于分区映射。



您的第一个问题在于定制工具提示,以便显示数据集中的一些变量(包括那些未映射到美学的变量)。

在您的UPDATE#3中,您将介绍: text = paste(Province:,NAME_1)到你的aes中。如果您想添加第二行自定义变量或文本,只需将其添加到括号中: text = paste(Province:,NAME_1,Example III:,example1)要在两者之间添加一个换行符,在之前添加< br> ,例如: text =粘贴(Province:,NAME_1,< br>,Example III:,example1)
$ b 第二个问题是定制工具提示,所以它不显示其他(默认)变量(映射到美学,如坐标)。

我发现这非常简单,除了 ggplotly()函数为我完成了这个技巧: ggplotly(gg,tooltip = c(text)) In我的情况是,它删除了工具提示中显示的所有默认变量,只显示了上面定制的 text 指定的变量。您可以通过执行 ggplotly(gg,tooltip = c(text,x))来添加其他变量。工具提示中显示的变量顺序将为与工具提示参数中指定的顺序相同。我发现这里记录: https://github.com/ropensci/plotly /blob/master/R/ggplotly.R



这个解决方案对我来说(原则上)使用R 3.1.1和绘图3.4.13 p>

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. 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:

#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. Using this updated version (4.0.0) I've made it apart of the way there.

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.

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. 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. 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. HOWEVER, when I tried to add additional label changes using text2=paste("Example III:", example1), the following occurs:

Notice that it cannot render text2 the same way it renders text1. 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:

I'm beginning to think something as simple as toggling "legend" options in plotly's ggplot conversion is impossible. UPDATE #4: So I decided to approach this another way. 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. So I went ahead and relabeled the variables. It works -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(). 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. 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)

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. 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. I found this documented here: 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中的ggplot2编辑工具提示中的标签以绘制阴谋地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆