Conquering the World of Shiny Apps: How to Get GoogleVis to Recognise All Countries
Image by Pall - hkhazo.biz.id

Conquering the World of Shiny Apps: How to Get GoogleVis to Recognise All Countries

Posted on

Are you tired of dealing with incomplete maps and frustrated users in your Shiny app? Do you dream of a world where GoogleVis can proudly display every country, no matter how small or remote? Well, buckle up, fellow developer, because today we’re going to embark on a thrilling adventure to conquer this common pitfall and make your Shiny app a global sensation!

The Problem: Incomplete Country List

If you’ve worked with GoogleVis in Shiny, you’ve probably encountered the issue of missing countries. It’s frustrating, to say the least. You create a beautiful map, only to realise that some countries are mysteriously absent. But fear not, my friend, for this article will guide you through the process of coaxing GoogleVis into recognising all 196 countries (yes, 196, not 195, not 194, but 196).

Why Does This Happen?

Before we dive into the solution, let’s quickly explore the reasons behind this issue. The main culprit is the way GoogleVis handles country names. You see, GoogleVis relies on the ISO 3166-1 alpha-2 codes, which are two-letter codes assigned to each country. However, not all countries have these codes, and some have multiple codes (e.g., Taiwan has both “TW” and “ROC”). This leads to confusion, and GoogleVis simply omits the countries it can’t identify.

The Solution: ISO 3166-1 alpha-2 Codes to the Rescue!

The solution lies in creating a comprehensive list of country names and their corresponding ISO 3166-1 alpha-2 codes. But don’t worry, you won’t have to manually create this list (although, if you’re feeling adventurous, you can try). We’ll use the `countrycode` package in R to generate the list for us.

library(countrycode)

# Create a data frame with country names and ISO 3166-1 alpha-2 codes
country_list <- data.frame(
  country = tolower(countrycode::countrycodes[]$country.name),
  iso_a2 = countrycode::countrycodes[]$iso2c
)

# Remove duplicates and sort the list
country_list <- country_list[!duplicated(country_list$country), ]
country_list <- country_list[order(country_list$country), ]

Now, let’s save this data frame as a CSV file, which we’ll use later in our Shiny app.

write.csv(country_list, "country_list.csv", row.names = FALSE)

Shiny App Time!

Create a new Shiny app, and in the `ui.R` file, add the following code:

library(shiny)
library(googleVis)

ui <- fluidPage(
  titlePanel("GoogleVis Country Map"),
  sidebarLayout(
    sidebarPanel(
      selectInput("country", "Select a country:", choices = ""),
      actionButton("go", "Go!")
    ),
    mainPanel(
      googleVisOutput("map")
    )
  )
)

In the `server.R` file, add the following code:

server <- function(input, output) {
  country_list <- read.csv("country_list.csv", stringsAsFactors = FALSE)
  
  output$map <- renderGooglevis({
    req(input$go)
    country <- input$country
    gv <- gvisGeoMap(country_list, "iso_a2", "country",
                      hovervar = "country",
                      options=list(gvis.map.path="https://maps.google.com/"))
    gv
  })
  
  observeEvent(input$go, {
    updateSelectInput(session, "country", choices = country_list$country)
  })
}

In this code, we first read in the `country_list.csv` file we created earlier. Then, we use the `gvisGeoMap` function to create the GoogleVis map. The `hovervar` argument specifies the column in the data frame to use for the hover text, and the `options` list sets the map path to Google Maps.

Adding a Twist: Conditional Formatting

Now, let’s take it up a notch by adding conditional formatting to our map. We’ll use the `gvisGeoMap` function’s `colorVar` argument to specify a column in the data frame that contains the values for the conditional formatting.

server <- function(input, output) {
  country_list <- read.csv("country_list.csv", stringsAsFactors = FALSE)
  
  # Add a new column for conditional formatting
  country_list$metric <- runif(nrow(country_list), 0, 100)
  
  output$map <- renderGooglevis({
    req(input$go)
    country <- input$country
    gv <- gvisGeoMap(country_list, "iso_a2", "country",
                      hovervar = "country",
                      colorvar = "metric",
                      options=list(gvis.map.path="https://maps.google.com/"))
    gv
  })
  
  observeEvent(input$go, {
    updateSelectInput(session, "country", choices = country_list$country)
  })
}

In this example, we added a new column called `metric` with random values between 0 and 100. We then passed this column to the `colorvar` argument, which will colour the countries on the map based on the values in the `metric` column.

The Grand Finale: Running the App

Run the Shiny app by clicking the “Run App” button in RStudio or by executing the following command in the terminal:

shinyApp(ui = ui.R, server = server.R)

Open a web browser and navigate to http://localhost:8100. You should see a beautiful map with all 196 countries, each with its corresponding ISO 3166-1 alpha-2 code. Select a country from the dropdown menu, click the “Go!” button, and marvel at the magic of GoogleVis.


Country ISO 3166-1 alpha-2 code
Afghanistan AF
Åland Islands AX
Albania AL

Voilà! You’ve successfully tamed the GoogleVis beast and made it recognise all countries in your Shiny app. Pat yourself on the back, my friend, and enjoy the admiration of your users.

Troubleshooting Tips

  • Make sure to update the `country_list.csv` file if you add or remove countries from your data frame.
  • If you encounter issues with country names or ISO codes, double-check the `country_list.csv` file for errors or inconsistencies.
  • For optimal performance, consider using a more efficient data storage solution, such as a database or a data.table.

That’s it, folks! With this comprehensive guide, you should now be able to create a Shiny app that proudly displays all 196 countries, complete with conditional formatting and hover text. Remember to stay curious, keep experimenting, and always keep your users in mind.

Conclusion

In conclusion, getting GoogleVis to recognise all countries in a Shiny app requires a combination of clever data manipulation and clever coding. By following this guide, you’ve taken a significant leap towards creating an engaging and informative Shiny app that will leave your users in awe. So go ahead, share your newfound knowledge with the world, and remember: in the world of Shiny apps, the possibilities are endless!

Happy coding, and see you in the next adventure!

Here are the 5 Questions and Answers about “How to get googlevis to recognise all countries in shiny app” :

Frequently Asked Question

Get ready to conquer the world of googlevis and Shiny apps!

Q1: What’s the deal with googlevis not recognizing all countries in my Shiny app?

It’s likely because googlevis uses ISO 3166-1 alpha-2 country codes, which can be quite finicky. Make sure you’re using the correct codes for each country. You can use the `countrycode` package in R to help with the conversion.

Q2: How do I specify the country codes in my Shiny app?

You can specify the country codes using the `region` argument in the `gvisGeoChart` function. For example, `region = “ISO-3166-1″` will tell googlevis to use the ISO 3166-1 alpha-2 country codes.

Q3: What if I have a dataset with country names in a different format?

No problem! You can use the `countrycode` package to convert your country names to ISO 3166-1 alpha-2 codes. For example, `countrycode(“United States”, “country.name”, “iso2c”)` will return “US”.

Q4: How do I ensure that googlevis recognizes all countries, including those with special characters or accents?

Make sure to use UTF-8 encoding in your Shiny app to handle special characters and accents. You can also use the `iconv` function to convert your country names to UTF-8.

Q5: What if I still encounter issues with googlevis not recognizing certain countries?

Double-check your country codes and data formatting, and make sure you’ve updated your googlevis and Shiny packages to the latest versions. If all else fails, try using a different geochart package, such as `leaflet` or `plotly`.

Leave a Reply

Your email address will not be published. Required fields are marked *