RStudio Not Rendering Sankey - r

Looking for some help identifying why this code would not render the Sankey in RStudio viewer or otherwise. I think it could be a problem with my R version (3.3.1)...the packages I'm using were built under 3.3.1. Unfortunately my organization takes awhile to update the enterpirse...
library(devtools)
library(rjson)
library(igraph)
library(rCharts)
x = read.csv('./R/dataforR.csv', header=TRUE)
colnames(x) <- c("UID","From", "To", "Avg.Hours")
sankeyPlot <- rCharts$new()
sankeyPlot$set(
data = x,
nodeWidth = 115,
nodePadding = 110,
layout = 132,
width = 1500,
height = 1300,
units = "hrs",
title = "New Sankey"
)
sankeyPlot$setLib('http://timelyportfolio.github.io/rCharts_d3_sankey')
sankeyPlot

The address in sankeyPlot$setLib('http://timelyportfolio.github.io/rCharts_d3_sankey') is incorrect.
As per this SO question, it should be:
sankeyPlot$setLib('http://timelyportfolio.github.io/rCharts_d3_sankey/libraries/widgets/d3_sankey')

Related

r reactable output as html and png created paragraph break symbol which was unseen in r markdown preview

This is the first time I tried reactable and raising questions in stack overflow. I apologise in advance if anything is unclear.
I was working on a simple reactable, and while the preview in RStudio looks fine, when I tried to save it as png and html, 5 paragraph break symbol (pilcrow) appears on the top of the output.
This is a screenshot of preview in R Studio:
This is the actual output:
Not sure if it's related, but I got the below warning during output as well:
[WARNING] Deprecated: --self-contained. use --embed-resources --standalone
I tried others' reactable, and it produced the same paragraph break symbol in the html and png output.
Below are the codes I used:
# Libraries
library(dplyr)
library(ggplot2)
library(tidyr)
library(reactable)
library(reactablefmtr)
library(utf8)
library(gt)
library(htmlwidgets)
library(webshot2)
webshot::install_phantomjs()
# data
Rank <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Name <- c('Red Lion', 'Crown', 'Royal Oak', 'White Hart', 'Railway', 'Plough', 'Swan', 'White Horse', 'Kings Arm', 'Ship')
Number <- c(519, 485, 406, 300, 280, 278, 276, 271, 237, 230)
Popular_Pub_Name <- data.frame(Rank, Name, Number)
# reactable
table <- reactable(Popular_Pub_Name,
defaultSorted = "Number",
width = 500,
defaultColDef = colDef(align = "left"),
columns = list(
Rank = colDef(
width = 60
),
Name = colDef(
name = "Pub Name",
width = 100
),
Number = colDef(
defaultSortOrder = "desc",
width = 200,
cell = data_bars(Popular_Pub_Name,
fill_color="#7814ff",
text_position = "outside-end",
bar_height = 10,
text_size = 12,
min_value=0,
max_value =600,
background = "transparent"
)
)))
table1 <- table %>%
add_title("UK's Most Popular Pub Name"
)
# output
html <- "pub_name1.html"
saveWidget(table1, html)
# save as png
webshot(html, "pub_name1.png", zoom = 3, vwidth = 500)

How to add title to a networkD3 visualisation when saving as a web page?

I have created a interactive visualisation using the following code:
library(networkD3)
nodes = data.frame("name" = c("node1", "node2","node3", "node4", "node5", "node6", "node7"))
links = as.data.frame(matrix(c(
0,1,7937,
0,2,6990,
0,3,2483,
1,4,2120,
2,4,666,
3,4,282,
1,5,4583,
2,5,5657,
3,5,731,
1,6,1234,
2,6,756,
3,6,1470), byrow = TRUE, ncol = 3))
names(links) = c("source", "target", "value")
sankey <- sankeyNetwork(Links = links, Nodes = nodes,
Source = "source", Target = "target",
Value = "value", NodeID = "name",
fontSize= 12, nodeWidth = 15)'
This is my first time using the networkD3 package (or any interactive package for that matter) and from playing around I found that to keep it interactive it has to be published as a webpage (or is there another way??) but looking through the documentation for the package I can't see a way to add a title or a caption / comments. I want to share this piece of work round so need to explain what each level means on the published webpage ideally
There is no feature built-in to networkD3 to add titles or captions, but you can use functions in the htmlwidgets package to prepend or append content to an htmlwidget. There are numerous options, but for example....
library(htmlwidgets)
library(htmltools)
sankey <- htmlwidgets::prependContent(sankey, htmltools::tags$h1("Title"))
sankey <- htmlwidgets::appendContent(sankey, htmltools::tags$p("Caption"))
Responding to the comment, "I ended up using this to add a title, but it keeps pushing my viz down and cutting the bottom off. This stays off even when saving as a webpage. Is there anyway I can stop this from happening?"
I tried the suggested reply of adding sankey$sizingPolicy$viewer$fill <- FALSE, however, it made my sankey smaller than I wanted it. I found out that you can adjust the width and height of the Sankey prior to adding the HTML widget by adding width=(desired width) and height=(desired height) and this creates the space to then add in the title and the comment, as suggested by CJ Yetman.
library(networkD3)
library(htmlwidgets)
library(htmltools)
nodes = data.frame("name" = c("node1", "node2","node3", "node4", "node5", "node6", "node7"))
links = as.data.frame(matrix(c(
0,1,7937,
0,2,6990,
0,3,2483,
1,4,2120,
2,4,666,
3,4,282,
1,5,4583,
2,5,5657,
3,5,731,
1,6,1234,
2,6,756,
3,6,1470), byrow = TRUE, ncol = 3))
names(links) = c("source", "target", "value")
sankey <- sankeyNetwork(Links = links, Nodes = nodes,
Source = "source", Target = "target",
Value = "value", NodeID = "name",
fontSize= 12, nodeWidth = 15,
width= 900, height=600)
sankey <- htmlwidgets::prependContent(sankey, htmltools::tags$h1("Title"))
sankey <- htmlwidgets::appendContent(sankey, htmltools::tags$p("Caption"))
sankey

Having trouble plotting location variable in R using googleVis package?

So I have this dataset of bike thefts (link: https://www.opendataphilly.org/dataset/bicycle-thefts/resource/f9809381-76f6-4fca-8279-621e088ddaa0).
I tried this code to plot location variable in R. the code runs, and i am taken to a new window but it is blank. Nothing appears.
What am I doing wrong?
Here's what I tried:
I renamed the dataset as bt
install.packages("ggmap")
library(ggmap)
install.packages("googleVis")
library(googleVis)
bt$LOCATION_B <- as.character(bt$LOCATION_B)
bt$geom <- gsub(",", ":", bt$geom)
placeNames <- as.character(bt$LOCATION_B)
plotData <- data.frame(name = placeNames, latLong = unlist(bt$geom))
sites <- gvisMap(plotData, locationvar = "latLong", tipvar = "name",
options = list(displayMode = "Markers", mapType = "terrain",
colorAxis = "{colors:['red', 'blue']}", height = 600,
useMapTypeControl=TRUE, enableScrollWheel='TRUE'))
plot(sites)

Change Font Size on rCharts Sankey Diagram

I'm using the following code to create a Sankey Diagram using rCharts. I wish to increase the font size of the text printed on the Sankey Diagram. I can't find a manual to show me how to do this. Thoughts?
rm(list = ls())
require(reshape)
require(rCharts)
require(rjson)
target <- c('TMF', 'TMF', 'TMF','Evaporation','Mill Reclaim','Void Losses','Seepage')
source <- c('Precipitation & Run Off','Slurry','Other','TMF','TMF','TMF','TMF')
value <- c(638,1610,755,118,1430,466,2)
x <- data.frame(target,source,value)
sankeyPlot <- rCharts$new()
sankeyPlot$set(
data = x,
nodeWidth = 10,
nodePadding = 10,
layout = 32,
width = 1100,
height = 675,
units = "cubic metres",
title = "Sankey Diagram"
)
sankeyPlot$setLib('http://timelyportfolio.github.io/rCharts_d3_sankey')
sankeyPlot
Based on this answer you can add scripts to customize your plots. To change the text-size, you could add:
sankeyPlot$setTemplate(
afterScript = "
<script>
d3.selectAll('#{{ chartId }} svg text')
.style('font-size', '55')
</script>
")
I was able to change the font size after creating the sankey diagram by setting the fontSize option:
#create sankey diagram
p<-sankeyNetwork(...)
#the default font size
> p$x$options$fontSize
[1] 7
#set desired font size
p$x$options$fontSize<-10

Interactive R Markdown Document with ggmap

I'm working with the ggmap tutorial by Manuel Amunategui over at http://amunategui.github.io/ggmap-example/. It is a wonderful introduction to the ggmap package and thankfully I understand his tutorial.
However, I am also trying to make this material interactive through R markdown. When I run the below document, for some reason the rendering of the map is of very low quality. In my standard .R script the image produced is way better. Any thoughts as to what might cause the drastic difference in quality?
Also, in R Markdown, is it possible to have custom sizing of the images as well as placement? I am specifically interested in making the map larger and/or displaying another map with it side-by-side.
This first block of code is just to get your hands on the data if desired.
#install.packages("RCurl"); install.packages("xlsx"); install.packages("zipcode"); install.packages("ggmap")
library(RCurl)
library(xlsx)
# NOTE if you can't download the file automatically, download it manually at:
#'http://www.psc.isr.umich.edu/dis/census/Features/tract2zip/'
urlfile <-'http://www.psc.isr.umich.edu/dis/census/Features/tract2zip/MedianZIP-3.xlsx'
destfile <- "census20062010.xlsx"
download.file(urlfile, destfile, mode="wb")
census <- read.xlsx2(destfile, sheetName = "Median")
#census <- read.xlsx2(file = "census20062010.xlsx", sheetName = "Median")
head(census)
# clean up data
# census <- census[c('Zip','Median..', 'Pop')]
names(census) <- c('Zip','Median', 'Pop')
census$Median <- as.character(census$Median)
census$Median <- as.numeric(gsub(',','',census$Median))
census$Pop <- as.numeric(gsub(',','',census$Pop))
head(census)
# get geographical coordinates from zipcode
library(zipcode)
data(zipcode)
census$Zip <- clean.zipcodes(census$Zip)
census <- merge(census, zipcode, by.x='Zip', by.y='zip')
census$location <- paste0(census$city, ", ", census$state)
names(census) <- sapply(names(census), tolower)
# saved census to census.rdata at this point...
The next chunk of code below is what is in the markdown file.
```{r, message=FALSE, echo=FALSE}
library(ggmap)
library(ggplot2)
load("census.rdata")
inputPanel(
textInput("loc", label = "Location", value = "Orlando, FL"),
sliderInput("zoom", label = "Zoom Level",
min = 1, max = 12, value = 10, step = 1)
)
renderPlot({
census2 <- census[census$location == input$loc,]
map <- get_map(location = input$loc,
zoom = input$zoom,
maptype = 'roadmap',
source = 'google',
color = 'color',
filename = "ggmapTemp")
print(ggmap(map) +
geom_point(
aes(x=longitude, y=latitude,
show_guide = TRUE, size=Median),
data=census2, colour = I('red'), na.rm = T)
)
})
```
Thanks for your help!

Resources