plotting barchart in popup using leaflet library
Asked Answered
A

2

10

Quick question all. I have some data in sql server which i have loaded into RStudio. I have made a barchart for the data and now i am using leaflet library with the use of latitude and longitude to plot a point on the map. I want to be able to use popup to show a barchart in it when the user clicks on the point.

BarChart code (maybe this is a problem because i am using googleVis library so not sure if i can use this in the popup. but again this is the most appropriate bar graph i can make and need- other suggestions could be helpful as i am not a professional in R libraries yet)

Switzerland <- sqlQuery(con, "sql query")
SwitzerlandChart <- gvisBarChart(Switzerland, options = list(height=200))

For the graph plot the code is:

m <- leaflet() %>%
  addTiles() %>%  # Add default OpenStreetMap map tiles
  addCircles(lng=8.498868, lat=46.9221, popup=paste(plot(SwitzerlandChart)))

When i run this code it opens a webpage to view my barplot. Then i run the following:

m #Prints the graph

This prints the graph with the point in the desired location but the popup shows me a webpage instead which also only i can open.

I want to be able to plot the bargraph inside the popup please.

Hope someone can help

Ardith answered 2/9, 2015 at 11:58 Comment(2)
Please provide sample data.Ironlike
my select statement is: SELECT distinct region + ', ' + city as Location, count(country) as [CountVis] FROM DATABASE WHERE Country = 'Switzerland' GROUP BY country, region, city. Data is: Location- Geneva, Zurich; CountVis- 1, 15 (this is what i plot the barchart with.Ardith
O
12

Maybe a little late but here's a solution. The addPopups() function in library(leaflet) seems to be able to handle .svg files. Therefore, you could simply save your plot using svg() and then read it again using readLines(). Here's a reproducible example using library(mapview):

library(lattice)
library(mapview)
library(sp)

data(meuse)
coordinates(meuse) <- ~x+y
proj4string(meuse) <- CRS("+init=epsg:28992")

clr <- rep("grey", length(meuse))

fldr <- tempfile()
dir.create(fldr)

pop <- lapply(seq(length(meuse)), function(i) {

  clr[i] <- "red"
  p <- xyplot(meuse$cadmium ~ meuse$copper, 
              col = clr, pch = 20, alpha = 0.7)

  svg(filename = paste(fldr, "test.svg", sep = "/"), 
      width = 250 * 0.01334, height = 250 * 0.01334)
  print(p)
  dev.off()

  tst <- paste(readLines(paste(fldr, "test.svg", sep = "/")), collapse = "")

  return(tst)

})

mapview(meuse, popup = pop, cex = "cadmium")

You will see that each popup is a scatterplot. As for a leaflet example, consider this:

content <- pop[[1]]
leaflet() %>% addTiles() %>%
  addPopups(-122.327298, 47.597131, content,
            options = popupOptions(closeButton = FALSE)
  )

In case you need the plot to be interactive, you could have a look at library(gridSVG) which is able to produce interactive svg plots from e.g. lattice or ggplot2 plots.

UPDATE:

library(mapview) now has designated functionality for this:

  • popupGraph: to embed lattice, ggplot2 or interactive hatmlwidgets based plots.
  • popupImage: to embed local or remote (web) images

This is currently only available in the development version of mapview which can be installed with:

devtools::install_github("environmentalinformatics-marburg/mapview", ref = "develop"
Ozonize answered 26/3, 2016 at 16:1 Comment(5)
is it possible to combine popupGraph and popupTable? For example: mapview(meuse, popup = popupGraph(p, type = "svg", width = 3, height = 2.5), popup = popupTable(meuse, z="cadmium")) does not work. I would like to add an image above the table.Gaze
Nope, this is not possible with any of the currently available functions in mapview. I think it could be possible though. Basically, one would need to combine the two html strings from the popup* functions.Ozonize
@Gaze Turns out you can just paste them together library(mapview) library(lattice) poptab = popupTable(breweries[1, ]) popgrph = popupGraph(graphs = lattice::xyplot(1:10 ~ 10:1)) tst = paste(popgrph[[1]], poptab[[1]]) mapview(breweries[1, ], popup = tst) Ozonize
I tried to use mapview::popupGraph and I get a result saying it is now deprecated. And leaflet does not have popupGraphBlindworm
The first example provided above causes R to crash. It displays something for a little while in the plot window and looks like it may be working but the CPU gets going with a bit of intensity and after a few seconds R shutsdownBlindworm
K
4

This may be a little late too, but here is a full leaflet implementation. I first create the plot and then use the popupGraph function to add it in.

# make a plot of the two columns in the dataset
p <- xyplot(Home ~ Auto, data = Jun, col = "orange", pch = 20, cex = 2)

# make one for each data point
p <- mget(rep("p", length(Jun)))

# color code it so that the corresponding points are dark green
clr <- rep("orange", length(Jun))
p <- lapply(1:length(p), function(i) {
  clr[i] <- "dark green"
  update(p[[i]], col = clr)
})


# now make the leaflet map
m1 <- leaflet() %>%
  addTiles() %>%
  setView(lng = -72, lat = 41, zoom = 8) %>%


  # add the markers for the Jun dataset
  # use the popupGraph function
  addCircleMarkers(data = Jun, lat = ~Lat, lng = ~Lon,
                   color = ~beatCol(BeatHomeLvl), popup = popupGraph(p),
                   radius = ~sqrt(BeatHome*50), group = 'Home - Jun') %>%


  # layer control
  addLayersControl(
    overlayGroups = c('Home - Jun'
    ),
    options = layersControlOptions(collapsed = F)
  ) %>%



  # legend for compare to average

  addLegend('bottomright', pal = beatCol, values = last$BeatTotalLvl,
            title = 'Compare<br>Quote Count to<br>3Mos State Avg',
            opacity = 1)

m1

Here is the output. enter image description here

Kennykeno answered 25/10, 2018 at 14:46 Comment(5)
You can also make the plots in ggplot and add them: p <- ggplot(Jun, aes(x = Auto, y = Home)) + geom_point(col = "orange", pch = 20, cex = 2) + geom_smooth(method = 'lm', formula = y~x) + xlim(0,1500)Kennykeno
When I run the lapply command, I get: Error in update.default(p[[i]], col = clr) : need an object with call component Any ideas why?Foist
@Foist you need to make sure that you have the sp, lattice and map view library installed.Kennykeno
I tried to use mapview::popupGraph and I get a result saying it is now deprecated. And leaflet does not have popupGraphBlindworm
It is a warning, but you need to read it. The warning indicates to use 'leafpop::popupGraph so you need to install the leafpop package.Kennykeno

© 2022 - 2024 — McMap. All rights reserved.