Week 2 Assignment - Johns Hopkins University - Coursera

Overview

The assignment involves creating an interactive map using the leaflet package in R to display the capitals of Indian states and union territories. The script includes: - Loading the necessary library. - Defining a data frame containing state and capital information along with their latitude and longitude coordinates. - Generating a Leaflet map with markers to indicate capital cities. Popups display the state name and the capital name in brackets.

This assignment demonstrates how to create an interactive map visualization in R effectively showcasing geographic data.


Step 1: Load Required Library

First, load the leaflet library, which provides functions for creating interactive maps.

# Load the leaflet library
library(leaflet)


# Define the data frame
indian_states <- data.frame(
  state = c(
    "Andaman and Nicobar Islands", "Andhra Pradesh", "Arunachal Pradesh", 
    "Assam", "Bihar", "Chandigarh", "Chhattisgarh", 
    "Dadra and Nagar Haveli and Daman and Diu", "Delhi", "Goa", 
    "Gujarat", "Haryana", "Himachal Pradesh", "Jammu and Kashmir", 
    "Jharkhand", "Karnataka", "Kerala", "Ladakh", "Lakshadweep", 
    "Madhya Pradesh", "Maharashtra", "Manipur", "Meghalaya", 
    "Mizoram", "Nagaland", "Odisha", "Puducherry", "Punjab", 
    "Rajasthan", "Sikkim", "Tamil Nadu", "Telangana", "Tripura", 
    "Uttar Pradesh", "Uttarakhand", "West Bengal"
  ),
  capital = c(
    "Port Blair", "Amaravati", "Itanagar", "Dispur", "Patna", 
    "Chandigarh", "Raipur", "Daman", "New Delhi", "Panaji", 
    "Gandhinagar", "Chandigarh", "Shimla", "Srinagar", "Ranchi", 
    "Bengaluru", "Thiruvananthapuram", "Leh", "Kavaratti", "Bhopal", 
    "Mumbai", "Imphal", "Shillong", "Aizawl", "Kohima", "Bhubaneswar", 
    "Puducherry", "Chandigarh", "Jaipur", "Gangtok", "Chennai", 
    "Hyderabad", "Agartala", "Lucknow", "Dehradun", "Kolkata"
  ),
  lat = c(
    11.6234, 16.5062, 27.0978, 26.1433, 25.5941, 30.7333, 
    21.2514, 20.3974, 28.6139, 15.4909, 23.2156, 29.0588, 
    31.1048, 34.0837, 23.3441, 12.9716, 8.5241, 34.1526, 
    10.5667, 23.2599, 19.0760, 24.8170, 25.5788, 23.7271, 
    25.6751, 20.2961, 11.9416, 31.1471, 26.9124, 27.3389, 
    13.0827, 17.3850, 23.8315, 26.8467, 30.3165, 22.5726
  ),
  lng = c(
    92.7265, 80.6480, 93.6237, 91.7898, 85.1376, 76.7794, 
    81.6296, 72.8328, 77.2090, 73.8278, 72.6369, 76.0856, 
    77.1734, 74.7973, 85.3096, 77.5946, 76.9366, 77.5770, 
    72.6167, 77.4126, 72.8777, 93.9368, 91.8933, 92.7176, 
    94.1086, 85.8245, 79.8083, 75.3412, 75.7873, 88.6065, 
    80.2707, 78.4867, 91.2868, 80.9462, 78.0322, 88.3639
  )
)


# Create the Leaflet map
my_map <- leaflet(indian_states) %>%
  addTiles() %>%
  addMarkers(
    ~lng, ~lat, 
    popup = paste(indian_states$state, "(", indian_states$capital, ")")
  )


# Display the map
my_map