У меня есть два файла R, mapio.R
и main.R
.mapio.R
содержит функцию (plotPointsOnMap), которая позволяет мне генерировать ggplot.Затем я передаю график на ggplotly
, чтобы преобразовать его в сюжет.При наведении курсора на точки на карте я вижу дубликаты информации во всплывающей подсказке, как показано ниже.
Как показать только один набор lat
и long
вместо отображения двух?
mapio.R
library(maps)
library(ggmap)
library(ggplot2)
getCoordinatesFromCSV <- function(filePath, latName, longName) {
# Load and read the CSV files
csvData <- read.csv(filePath, header = TRUE, sep = ",")
# Get the longitude and latitude
coordinates <- subset(csvData, select = c(latName, longName))
# Separate the longitude and latitudes
latitude <- coordinates$Latitude
longitude <- coordinates$Longitude
# Return the coordinates as a list
return(list(latitude, longitude))
}
generateGeomPoints <- function(coordinateList, colorLegend) {
# Get the longitude and latitude
latitude <- coordinateList[[1]]
longitude <- coordinateList[[2]]
# Construct a dataframe
dataframe <- data.frame(lat = latitude, lon = longitude)
# Return the constructed point
return(geom_point(data = dataframe, aes(x = lon, y = lat, color = colorLegend)))
}
plotPointsOnMap <- function(location, zoom, mapPoints, labelList) {
# NOTE: The labelList should be in the following format: x-axis
# label, y-axis label, legend name and title of the map.
# Get map of specified location
map <- get_map(location = location, zoom = zoom)
# Dynamically append the layers to the map
mapPlot <- ggmap(map)
for (i in range(1, length(mapPoints))) {
mapPlot <- mapPlot + mapPoints[[i]]
}
# Add axis labels and title
mapPlot <- mapPlot + labs(x = labelList[[2]], y = labelList[[1]]) +
ggtitle(labelList[[4]]) + labs(color = labelList[[3]]) +
theme(plot.title = element_text(hjust = 0.5))
# Return the map plot
return(mapPlot)
}
main.R
source("mapio.R")
library(plotly)
# Get coordinates from CSV file
orderCoor <- getCoordinatesFromCSV("../data/orders.csv", "Latitude", "Longitude")
riderCoor <- getCoordinatesFromCSV("../data/riders.csv", "Latitude", "Longitude")
# Generate geom points
orderPoints <- generateGeomPoints(orderCoor, "Orders")
riderPoints <- generateGeomPoints(riderCoor, "Riders")
mapPoints <- c(orderPoints, riderPoints)
mapLabels <- c("Latitude", "Longitude", "Legend\n", "Map")
ggplotly(plotPointsOnMap('Singapore', 11, mapPoints, mapLabels))