Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I plot individual data points in a map using R/ leaflet?

I am trying to show the individual points in a given place, like a map equivalent of dot plot. I tried with leaflet library in R, but I am only able to map the size of the marker to the continuous variable. Is it possible to map the individual data points as clusters instead of mapping the size of the marker to the continuous variable?

My data looks like this

Lat,Lon,Place,People
19.877263,75.3390241,Aurangabad,1
20.2602939,85.8394548,Bhubaneshwar,2
30.7194022,76.7646552,Chandigarh,23
13.0801721,80.2838331,Chennai,25
11.0018115,76.9628425,Coimbatore,2
27.4844597,94.9019447,Dibrugarh,1
16.2915189,80.4541588,Guntur,1
17.3887859,78.4610647,Hyderabad,4
22.5677459,88.3476023,Kolkata,7
15.8309251,78.0425373,Kurnool,1
9.9256493,78.1228866,Madurai,1
like image 655
karthik2k2 Avatar asked Feb 25 '26 04:02

karthik2k2


2 Answers

You can use the following code to have dot plot

leaflet(df) %>% addTiles() %>%
  addCircleMarkers(lng = ~Lon, lat = ~Lat, 
             popup = ~Place)

enter image description here

Data

df = structure(list(Lat = c(19.877263, 20.2602939, 30.7194022, 13.0801721, 
11.0018115, 27.4844597, 16.2915189, 17.3887859, 22.5677459, 15.8309251, 
9.9256493), Lon = c(75.3390241, 85.8394548, 76.7646552, 80.2838331, 
76.9628425, 94.9019447, 80.4541588, 78.4610647, 88.3476023, 78.0425373, 
78.1228866), Place = structure(1:11, .Label = c("Aurangabad", 
"Bhubaneshwar", "Chandigarh", "Chennai", "Coimbatore", "Dibrugarh", 
"Guntur", "Hyderabad", "Kolkata", "Kurnool", "Madurai"), class = "factor"), 
    People = c(1L, 2L, 23L, 25L, 2L, 1L, 1L, 4L, 7L, 1L, 1L)), class = "data.frame", row.names = c(NA, 
-11L))
like image 73
Bappa Das Avatar answered Feb 26 '26 18:02

Bappa Das


leaflet works great with sf package. Taking a sample of your data points

lat <- c(19.877263, 20.2602939)
lon <- c(75.3390241, 85.8394548)
place <- c("Aurangabad", "Bhubaneshwar")

You can convert them in spatial object using sf package. For leaflet to give you tiles, you need to have WSG84 coordinates. I assumed your data were in this coordinate system.

library(sf)

df <- data.frame(lon, lat, place, stringsAsFactors = FALSE)
points <- st_as_sf(df, coords = c("lon", "lat"), crs = 4326)

Then it's easy to plot with leaflet. Assuming you want markers that popup the name of the place when you click

library(leaflet)
leaflet(df) %>% addTiles() %>% addMarkers(popup = ~ place)

enter image description here

like image 24
linog Avatar answered Feb 26 '26 18:02

linog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!