I created a function to produce ggplot choropleth maps, and it works:) However, I would like to remove the legend title (see picture below), since it now says 'I'. Furthermore, I would like to change the hover text into the variable labels as adapted in the Maps dataframe. However, when I merge this datafile with the shape file, en furthermore turn the MAPS dataframe into a readable format for ggplot, the variable labels are lost in the process. So, I would like to maintain the variable labels, and also want to incorporate the variable labels somehow in my function code, so I get the variable label of the fill= variable in my ggplotly hover text.
Below my code:
library(shiny)
library(shinydashboard)
library(ggplot2)
library(cbsodataR)
library(plotly)
library(sjlabelled)
library(expss)
library(tidyr)
library(tidyverse)
library(dplyr)
library(stringr)
library(rgdal)
library(plyr)
#Loading shapefile
ShapefileWijken <- readOGR("/Users/anne/Desktop/RondeVenen/ALGEMEEN_DATA/SHAPEFILES_DRV_6PC_5PC_Gemeente/WijkenEnBuurten/WijkenEnBuurten.shp")
#Opening data Dutch public database
Maps <- cbs_get_data("84583NED",
select=c("AantalInwoners_5","HuishoudensTotaal_28",
"Woningvoorraad_34", "GemiddeldInkomenPerInkomensontvanger_65", "Codering_3"))
#Merge data with shapefile
MAPS <- merge(ShapefileWijken,
Maps,
by.x = "BU_CODE",
by.y="Codering_3",
all=FALSE)
#Turn data into readable format for ggplot
MAPS@data$id <- rownames(MAPS@data)
TUSSEN <- fortify(MAPS, region="id")
CHOROPLETH <- merge(TUSSEN, MAPS@data, by="id")
library(plyr)
CHOROPLETH <- join(TUSSEN, MAPS@data, by="id")
###FUNCTION MAPS
ggplot_MAP <- function(i){
ggplot(data = CHOROPLETH, aes(x=long, y=lat, group = group)) +
geom_polygon(aes(fill=i), color="black") +
scale_fill_gradient(low="#99cc33", high="#009999") +
theme_void() +
theme(panel.border = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line.y=element_blank(), axis.line.x=element_blank(),
legend.title = element_blank())
}
#Adding gg plot choropleth map to shiny server
output$MAPINWONERS <- renderPlotly({
ggplotly(ggplot_MAP(CHOROPLETH$AantalInwoners_5)) %>% config(modeBarButtonsToRemove = c(
'sendDataToCloud', 'autoScale2d', 'resetScale2d', 'toggleSpikelines',
'hoverClosestCartesian', 'hoverCompareCartesian',
'zoom2d','pan2d','select2d','lasso2d','zoomIn2d','zoomOut2d'
), displaylogo=FALSE) %>% layout(dragmode=FALSE)
You can remove legend title by adding labs(fill=NULL)
immediately after your geom_polygon()
statement. To get the desired hover text, define text=paste("Text1",var1,"\nText2",var2)
inside the aes
of ggplot
; here Text1 and Text2 will be your desired text, and var1 and var2 will be your variable labels. Then include tooltip=c("text")
in ggplotly
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.