Highcharter Sankey - r

I am trying to create a sankey diagram using the following data frame and code:
UKvisits <- data.frame(origin=as.character(c(
"France", "Germany", "USA",
"Irish Republic", "Netherlands",
"Spain", "Italy", "Poland",
"Belgium", "Australia",
"Other countries", rep("UK", 5))),
visit=as.character(c(
rep("UK", 11), "Scotland",
"Wales", "Northern Ireland",
"England", "London")),
weights=c(
c(12,10,9,8,6,6,5,4,4,3,33)/100*31.8,
c(2.2,0.9,0.4,12.8,15.5)))
Highcharter line:
hchart(UKvisits, "sankey", hcaes(from = origin, to = visit, weight = weights))
This example has been copied from here: https://github.com/jbkunst/highcharter/blob/master/dev/highcharts-v6.R
For some reason whenever I run this, the plot screen remains white and nothing is being plotted.
I am trying this on R Studio version 1.1.423 (R Version: 4.3)
Does anybody have any idea why this is happening?

I had this same issue. First I got the javascript console error:
a is undefined
I wasn't using the correct function highchartOutput() in ui.R, then I got this in the javascript console:
Highcharts Error #17 The requested series type does not exist...
I found this post and a comment suggested installing the dev version of highcharter via:
devtools::install_github("jbkunst/highcharter")
And that fixed the issue for me, using the simple code from that post:
highchart() %>%
hc_chart(type = 'sankey') %>%
hc_add_series(
data = list(
list(from = 'AT', to = 'DE', weight = 10),
list(from = 'DE', to = 'CH', weight = 5),
list(from = 'DE', to = 'FI', weight = 5))
)
And I was able to work from there. Seems like you must use the dev version if you want to do a Sankey chart.

Related

How do I get plotly choropleth map locations to focus on Europe or certain European counties?

I am following the code from this website and trying to plot some data on an interactive map using ploty. Difference is I only have data for 6 euro pean countries. Currently the map is plotting for the entire world. How do I adjust the code to zoom in on either all of Europe or just the 6 European countries in the data. See sample code below. The country codes are from this link.
# Libraries
library(tidyverse)
library(plotly)
# Data
countries <- c("Germany", "Belgium", "Framce", "Italy", "Spain", "Poland")
codes <- c("DEU", "BEL", "FRA", "ITA", "ESP", "POL")
values <- c(100, 200, 300, 400, 500, 600)
df <- tibble(countries, codes, values)
# Maps
plot_geo(locations = df$codes) %>%
add_trace(
z = ~values,
locations = ~codes,
color = ~values
)

How to create R shiny interactive map without lat and long in the dataset

using leaflet package to create interactive map using r shiny. my dataset provides the names of countries but not the lat or long. how can i create this where the map can detect by country names
You can use a geojson map with the readOGR function, you can find the map on internet and link your dataset to it.
rgdal::readOGR(dsn = "GeoJSON map",
layer = "OGRGeoJSON",
stringsAsFactors = FALSE)
Below is an example based on this stackoverflow post to make an interactive map on R Shiny. The selected countries are in click.list$ids, see the output$selected_var below.
Your data
## packages ##
packages <- c("leaflet", "shiny", "shinydashboard")
newPackages <- packages[!(packages %in% installed.packages()[,"Package"])]
if(length(newPackages)) install.packages(newPackages)
lapply(packages, library, character.only = TRUE)
remove(packages, newPackages)
## map & data ##
Europe <- rgdal::readOGR(dsn = "https://data.opendatasoft.com/explore/dataset/european-union-countries#public/download/?format=geojson&timezone=Europe/Berlin",
layer = "OGRGeoJSON",
stringsAsFactors = FALSE)
data <- data.frame("name" = c("Austria", "Belgium", "Bulgaria", "Croatia", "Cyprus", "Czechia", "Denmark", "Estonia",
"Finland", "France", "Germany", "Greece", "Hungary", "Iceland", "Ireland", "Italy", "Latvia",
"Liechtenstein", "Lithuania", "Luxembourg", "Malta", "Netherlands", "Norway", "Poland", "Portugal",
"Romania", "Slovakia", "Slovenia", "Spain", "Sweden", "Switzerland", "Turkey", "United Kingdom"),
"polcapita" = c(0.0087928207, 0.0100464969, 0.0075375536, 0.0049040898, 0.0097860082, 0.0119440135, 0.0087740252,
0.0080851042, 0.0063462331, 0.0064707328, 0.0107846429, 0.0085740997, 0.0059612600, 0.0409884683,
0.0138830047, 0.0067616652, 0.0049423915, 0.0053782730, 0.0053461017, 0.0165884166, 0.0046052235,
0.0116079951, 0.0052533159, 0.0100049243, 0.0075509189, 0.0047028415, 0.0067531703, 0.0077087169,
0.0064795469, 0.0008881585, 0.0053907055, 0.0053085690, 0.0069728195))
# example if you need to change the name of a country
Europe#data[Europe#data$name == "Czech Rep.", ]$name <- "Czechia"
# example if you want to add datas to the map
Europe#data$polcapita <- merge(x = Europe#data, y = data, sort = FALSE)$polcapita
pal <- colorNumeric(c("Green", "Red"), Europe$polcapita)
The UI part
## create the UI ##
ui <- fluidPage(
# place the contents inside a box
shinydashboard::box(
width = 12,
title = "Click on the map!",
# separate the box by a column
column(width = 2,
shiny::actionButton(inputId = "clearHighlight",
icon = icon( name = "eraser"),
label = "Clear the Map",
style = "color: #fff; background-color: #D75453; border-color: #C73232")),
# separate the box by a column
column(width = 10,
leaflet::leafletOutput(outputId = "myMap", height = 850)),
column(width = 5,
textOutput("selected_var"))
)
)
The server part
## create the server ##
server <- function( input, output, session ){
# create foundational map
foundational.map <- shiny::reactive({
leaflet(Europe) %>%
fitBounds(-20, 65, 20, 39) %>%
addProviderTiles(providers$CartoDB.Positron) %>%
addPolygons(data = Europe,
layerId = Europe$name,
color = ~pal(polcapita),
group = "click.list",
weight = 2,
fillOpacity = 0.3,
opacity = 1,
smoothFactor = 0.2,
stroke = FALSE)
})
output$myMap <- renderLeaflet({
foundational.map()
})
# store the list of clicked polygons in a vector
click.list <- shiny::reactiveValues(ids = vector())
# add countries to selection
shiny::observeEvent(input$myMap_shape_click, {
click <- input$myMap_shape_click
if(click$id %in% click.list$ids){
click.list$ids <- click.list$ids[!click.list$ids%in%click$id]
leaflet::leafletProxy(mapId = "myMap") %>%
clearGroup("lin")
} else{
click.list$ids <- c(click.list$ids, click$id)
}
lines.of.interest <- Europe[ which(Europe$name %in% click.list$ids), ]
leaflet::leafletProxy(mapId = "myMap") %>%
addPolylines(data = lines.of.interest,
layerId = lines.of.interest$ids,
color = "#6cb5bc",
weight = 2,
opacity = 1,
group = "lin")
})
# Clear the map button
shiny::observeEvent( input$clearHighlight, {
output$myMap <- leaflet::renderLeaflet({
click.list$ids <- NULL
foundational.map()
})
})
# selected countries
output$selected_var <- renderText({
paste("You have selected", click.list$ids)
})
}
To run the server
## run shinyApp ##
shiny::shinyApp(ui, server)
I hope it answers your question !

R - Print specific country names in a map using rworldmap

I am creating a heatmap using the map of Europe in rworldmap package in R (since I don't know how to do this with ggmap or ggplot2).
I need to plot the country names of the countries that are present in my dataframe only, not all european countries. How can I do this?
My code:
library(RColorBrewer)
#getting colours
colourPalette <- brewer.pal(5,'RdPu')
library(rworldmap)
europe <- data.frame(
"country" = c("Greece",
"France",
"Spain",
"Italy",
"UK",
"Finland","Norway","Sweden",
"Germany",
"Romania"),
"x" = c(2.5, 3, 2.2, 1.8,2.32, 1.99, 2.01, 2.34, 1.88, 2.45))
matched <- joinCountryData2Map(europe, joinCode="NAME", nameJoinColumn="country")
mapParams <- mapCountryData(matched,
nameColumnToPlot="x",
mapTitle="my Titley",
addLegend=FALSE,
mapRegion="Europe"
,colourPalette=colourPalette,
oceanCol="#404040", missingCountryCol="#A0A0A0")
#adding legend
do.call(addMapLegend
,c(mapParams
,legendLabels="all"
,legendWidth=0.5
,legendIntervals="data"
,legendMar = 2))
labelCountries()
Using labelCountries() prints all country names and it's not readable.
Thanks
With a little bit help of this previously answer:
# get the coordinates for each country
country_coord<-data.frame(coordinates(matched),stringsAsFactors=F)
# label the countries
country = c("Greece",
"France",
"Spain",
"Italy",
"UK",
"Finland","Norway","Sweden",
"Germany",
"Romania")
#filter your wanted countrys
country_coord = country_coord[country,]
#insert your labels in plot
text(x=country_coord$X1,y=country_coord$X2,labels=row.names(country_coord))
you can add the country labels with text but you must extract the coordinates before from your matched coordinates.
Output:
You might play a bit with col = "color" in text, since some country can barely been read. Or maybe change the color scale in your map

Add 3d column values in hoverinfo when using ggplot2 object in ggplotly

my data frame:
structure(list(CNT = c("Albania", "Algeria", "Argentina (Ciudad Autónoma de Buenos)",
"Australia", "Austria", "B-S-J-G (China)", "Belgium", "Brazil",
"Bulgaria", "Canada"), Female = c(417.75, 363.07, 446.03, 490.99,
483.13, 528.19, 499.74, 369.55, 442.16, 511.14), Male = c(408.55,
356.5, 467.31, 496.76, 510.1, 534.01, 514, 385.04, 440.32, 520.17
)), .Names = c("CNT", "Female", "Male"), row.names = c(NA, 10L
), class = "data.frame")
I want to plot the data using a ggplot2 object and not plot_ly so that on hovering the values of all three variables are shown.
If I do the way I want only Male and Female appears on hovering:
p<-ggplot(df, aes(Female, Male)) +
geom_point()
ggplotly(p)
I want the country name to appear as well. Looking on the web I figure it out how to do in plot_ly:
plot_ly( df, x=df$Female , y=df$Male, text=df$CNT,
hoverinfo="text+x+y")
I want to achieve the same result but using a ggplot2 object as in the example above when using object p.
I think you are looking for this:
ggplot(df, aes(x = Female, y = Male, text = paste("CNT:", CNT))) + geom_point()
ggplotly()

How to create a world map in R with specific countries filled in?

I would like to use R to generate a very basic world map with a specific set of countries filled with a red colour to indicate that they are malaria endemic countries.
I have a list of these countries in a data frame but am struggling to overlay them on a world map.
I have tried using the wrld_simpl object and also the joinCountryData2Map method in the rworldmap package.
I would comment on this answer to prevent addition of a possibly redundant question but I do not have enough reputation at the moment, apologies for this.
https://stackoverflow.com/a/9102797/1470099
I am having difficulty understanding the arguments given to the plot() command - I wondered if there was just an easy way to tell R to plot all of the country NAMEs in my list on the wrld_simpl map instead of using grepl() etc. etc.
plot(wrld_simpl,
col = c(gray(.80), "red")[grepl("^U", wrld_simpl#data$NAME) + 1])
Using the rworldmap package, you could use the following:
library(rworldmap)
theCountries <- c("DEU", "COD", "BFA")
# These are the ISO3 names of the countries you'd like to plot in red
malDF <- data.frame(country = c("DEU", "COD", "BFA"),
malaria = c(1, 1, 1))
# malDF is a data.frame with the ISO3 country names plus a variable to
# merge to the map data
malMap <- joinCountryData2Map(malDF, joinCode = "ISO3",
nameJoinColumn = "country")
# This will join your malDF data.frame to the country map data
mapCountryData(malMap, nameColumnToPlot="malaria", catMethod = "categorical",
missingCountryCol = gray(.8))
# And this will plot it, with the trick that the color palette's first
# color is red
EDIT: Add other colors and include picture
## Create multiple color codes, with Burkina Faso in its own group
malDF <- data.frame(country = c("DEU", "COD", "BFA"),
malaria = c(1, 1, 2))
## Re-merge
malMap <- joinCountryData2Map(malDF, joinCode = "ISO3",
nameJoinColumn = "country")
## Specify the colourPalette argument
mapCountryData(malMap, nameColumnToPlot="malaria", catMethod = "categorical",
missingCountryCol = gray(.8), colourPalette = c("red", "blue"))
Try using googleVis package and use gvisGeoMap Functions
e.g.
G1 <- gvisGeoMap(Exports,locationvar='Country',numvar='Profit',options=list(dataMode='regions'))
plot(G1)
library(maptools)
data(wrld_simpl)
myCountries = wrld_simpl#data$NAME %in% c("Australia", "United Kingdom", "Germany", "United States", "Sweden", "Netherlands", "New Zealand")
plot(wrld_simpl, col = c(gray(.80), "red")[myCountries+1])

Resources