R Plotly Map,悬停文本从2个数据帧读取

时间:2018-04-25 13:51:09

标签: r ggplot2 plotly ggplotly

我目前有一张地图,它绘制了来自2个不同数据框的网站。我有一组红点和另一组蓝点。我可以从其中一个数据框中读取悬停文本但是当我将鼠标悬停在另一个颜色网站上时如何让它从另一个数据框中读取?

这是我到目前为止的代码

....获取世界多边形并提取英国

library(maps)
UK <- map_data("world") %>% filter(region=="UK")

png("JCMap.png")

JCMap <- ggplot() +
  geom_polygon(data = UK, aes(x=long, y = lat, group = group), fill="grey", color = "dark grey",alpha=0.3) +

  geom_point( data=sitesgeo, aes(x=long, y=lat), colour = 'blue', alpha = 0.5)+

  geom_point( data=SCBenchmarks, aes(x=long, y=lat), size = 2, colour = 'red') +

  theme_void() + ylim(50,59) + coord_map()+

  theme(legend.position="none")+

  ggtitle("Sites")+
  theme(
    plot.background = element_rect(fill = "#f5f5f2", color = NA),

    panel.background = element_rect(fill = "#f5f5f2", color = NA), 

    plot.title = element_text(size= 16, hjust=0.1, color = "#4e4d47", margin = margin(b = -0.1, t = 0.4, l = 2, unit = "cm")),

  )
print(JCMap)

JCMap

.....让它互动!

library(plotly)

p=SCBenchmarks %>%

  mutate( mytext=paste("Site: ", site_name, "\n", "Customers: ", claimant_key, sep="")) %>%

  ggplot() +

  geom_polygon(data = UK, aes(x=long, y = lat, group = group), fill="grey", alpha=0.3) +

  geom_point(data=sitesgeo,aes(x=long, y=lat), colour = 'blue', alpha = 0.5) +

  geom_point(aes(x=long, y=lat, text=mytext), colour = 'red', alpha = 1) +


  scale_size_continuous(range=c(1,15)) +

  scale_color_viridis(option="inferno", trans="log" ) +

  scale_alpha_continuous(trans="log") +

  theme_void() +

  ylim(50,59) +

  coord_map() +

  theme(legend.position = "none")


p=ggplotly(p, tooltip="text")

p

非常感谢任何帮助

干杯

1 个答案:

答案 0 :(得分:0)

我在朋友的帮助下想出了这个,可能不是最方便的方法,但它有效....看下面的代码

## plot

SCBenchmarks&lt; - SCBenchmarks%&gt;%

mutate(mytext = paste(site_name,&#34; \ n&#34;,&#34;客户:&#34;,customer_key,&#34; \ n&#34;,&#34;客户/人:&#34;,Cust_Per_Person,&#34; \ n&#34;,sep =&#34;&#34;))

最终&lt; - 最终%&gt;%

mutate(mytext = paste(site_name,&#34; \ n&#34;,district_name,&#34; \ n&#34;,&#34;客户:&#34;,Customer_Count,&#34; \ n&#34;,sep =&#34;&#34;))

##让静态图调用此文:

p&lt; - ggplot()+   geom_polygon(data = UK,aes(x = long,y = lat,group = group),fill =&#34; gray&#34;,alpha = 0.3)+

geom_jitter(data = Final,aes(x = long,y = lat,text = mytext),color =&#39; blue&#39;,alpha = 0.5)+

geom_jitter(data = SCBenchmarks,aes(x = long,y = lat,text = mytext),color =&#39; red&#39;,alpha = 1)+

scale_size_continuous(范围= c(1,15))+

scale_color_viridis(选项=&#34; inferno&#34;,trans =&#34; log&#34;)+

scale_alpha_continuous(trans =&#34; log&#34;)+

theme_void()+

ylim(50,59)+

coord_map()+

主题(legend.position =&#34;无&#34;)

p = ggplotly(p,tooltip =&#34; text&#34;)

P