How do you save a Highcharter chart as a gif in R? - r

I work with financial data that is mostly non-continuous, meaning market closing times and weekends need to be omitted from graphs.
Highcharter seems good at handling such data but how do you convert its charts into gifs? I know how to do this with ggplot and gganimate, but that combination does not handle financial data well.
Below is a simple line chart (of 10-year Treasury yields) done in Highcharter but I'd like to animate it and save it as a gif. Any help would be appreciated.
#load packages -------
library(here)
library(tidyverse)
library(highcharter)
# read in data -------
unemployment <- read_csv(here("data", "US 10-year Treasury.csv"))
# Line chart
data <- data.frame(unemployment)
hc <- data %>% hchart(
'line', hcaes(x = Date, y = Yield),
color = "steelblue"
)
hc

This functionality is not offered in the standard Highcharts library, therefore it has not been implemented in the Highcharter wrapper. Maybe R has some built-in tools for that gif export, unfortunately, I have no experience with it.

Related

Is there a way to have a highlighted chart as well as have interactivity of selecting elements in R?

I have come across a beautiful chart on this webpage: https://ourworldindata.org/coronavirus and interested to know if we can build the same chart in R with functionality of having highlighted series as well as selecting any line on hovering ?
I have build static highlighted charts using gghighlight but those are not interactive.
Plotly can help in interaction but I think they don't work with gghighlight.
So how can we have the combination of both highlight and interactivity in charts as in the link shared on top ?
Is it possible to achieve same results in R ? It would be really helpful if someone could share an example or link that can help.
(UPDATE: May be I can manually highlight lines by creating a factor column instead of using gghighlight and then pass it to ggplotly but then can ggplotly or some other library provide similar results on hover ?)
(NOTE: Not looking for animation. Just need highlighted, hover over interactive chart)
Below is the snapshot of same chart hovered over US (This chart is also similar to the one shared in World Economic Forum many times.)
Using plotly you can use highlight() to achive this.
This is a slightly modified example from here:
library(plotly)
# load the `txhousing` dataset
data(txhousing, package = "ggplot2")
# declare `city` as the SQL 'query by' column
tx <- highlight_key(txhousing, ~city)
# initiate a plotly object
base <- plot_ly(tx, color = I("black")) %>%
group_by(city)
# create a time series of median house price
time_series <- base %>%
group_by(city) %>%
add_lines(x = ~date, y = ~median)
highlight(
time_series,
on = "plotly_hover",
selectize = FALSE,
dynamic = FALSE,
color = "red",
persistent = FALSE
)

Mapping my data to a Zip Code area map in R

My data is like this:
ZIPcode Cases longi lati
43613 1 -83.604452 41.704307
44140 1 -81.92148 41.48982
46052 1 -86.470531 40.051603
48009 22 -83.213883 42.544619
48017 6 -83.151815 42.535396
48021 7 -82.946167 42.463894
48025 19 -83.265758 42.523195
I want to get a map similar to this (if you can see it) in R. The outline should be zipcodes and the shading should be according to number of cases, darker as cases increase.
I'm very new to R. Tried a lot of code I found online but can't get what I want. Any help is appreciated. Can this be done in base SAS ?
Thank you!
enter image description here
Definetly you can do it in R, I put together a reprex (reproducible example) for you. Key points:
You need to load into R a .shp file (or .geojson, .gpkg, etc.). That is an actual file with the outline of your map. For ZIPCODES I found a R package, tigris, that does that for you, if not you'll need to load it by yourself.
For handling mapping objects (load, transform, .etc), sf package is your best friend.
For plotting, in this example I used cartography, but you can use several different package, as ggplot2 or tmap.
Last line is that, given your data (and if I didn't get the ZIPCODEs wrong), a map as the one you shown (choropleth map) maybe is not the best options. Have a look here to see other alternatives.
library(sf) #Overall handling of sf objects
library(cartography) #Plotting maps package
#1. Create your data
yourdata <- data.frame(ZCTA5CE10=c("43613", "44140", "46052",
"48009","48017", "48021","48025"),
Cases=c(1,1,1,22,6,7,19)
)
#2. Download a shapefile (shp,gpkg,geojson...)
library(tigris) #For downloading the zipcode map
options(tigris_use_cache = TRUE)
geo <- st_as_sf(zctas(cb = TRUE, starts_with = yourdata$ZCTA5CE10))
#Overall shape of USA states
states <- st_as_sf(states(cb=TRUE))
#For plotting, all the maps should have the same crs
states=st_transform(states,st_crs(geo))
#3. Now Merge your data
yourdata.sf=merge(geo,yourdata)
#4. Plotting
par(mar=c(1,1,1,1))
ghostLayer(yourdata.sf)
plot(st_geometry(states), add=TRUE)
choroLayer(yourdata.sf,
var="Cases",
add=TRUE,
border = NA,
legend.pos = "right",
legend.frame = TRUE)
layoutLayer(title = "Cases by ZIPCODE",
theme = "blue.pal",
scale = FALSE,
sources = "Source; your question on SO",
author = "by dieghernan, 2020"
)
Created on 2020-02-27 by the reprex package (v0.3.0)

Disable rCharts animations

I am using rCharts and shiny in order to plot a variety of datasets. These datasets are dynamic and may in some cases be very big (10 000+ points in some cases). In these cases displaying the plot takes a lot of time (40s+).
Is there a way to generate an rCharts plot without the animations. This should significantly reduce the creating and rendering time of the plot.
I have looked trough the documentation (ltle that there is), but haven't found a way to do it.
The only thing that i have found is https://gist.github.com/timelyportfolio/10184829
I am using Polycharts, NVD3 and HighCharts.
EDIT: For highCharts i can do p$tooltip(enabled = F) and p$chart(animation = F). But any additional help would be appreciated, especially for Polycharts and NVD3
I am not a heavy user of Polycharts and Highcharts, so if you could add an example it would be helpful.
For NVD3 the variable is called transitionDuration.
An example of a chart without animations would be as follows:
library(rCharts)
hair_eye = as.data.frame(HairEyeColor)
p2 <- nPlot(Freq ~ Hair, group = 'Eye',
data = subset(hair_eye, Sex == "Female"),
type = 'multiBarChart')
p2$chart(transitionDuration=0)
p2

Dygraph multiple plots - turn them on and off with R and dySeries options

Good afternoon everyone,
I am discovering dyGraph for R and it is an amazing tool.
I need to plot only two variables ("Lifetime.Engaged.Users" & "Lifetime.Post.Total.Reach") of my 32 variables xts matrix.
My problem is as follow, even if I specify the two series I want to be plotted (with dySeries), dyGraph plots all the 32 variables, making the graph totally unreadable.
Here is the code.
# Read the insights from xls export
facebook.insight <- read.xlsx(
"Facebook Insights (Post Level)",
sheetIndex = 1)
# Convert the facebook insights to a Time Series with library(xts)
facebook.insight.TimeSerie <- xts(
facebook.insight[,-7],
order.by = facebook.insight$Posted
)
# Plot the desired series that are ("Lifetime.Engaged.Users" &
#"Lifetime.Post.Total.Reach") with dyGraph package
dygraph(facebook.insight.TimeSerie, main ="Facebook Insights") %>%
dySeries(name = "Lifetime.Engaged.Users", label = "Engaged Users") %>%
dySeries(name = "Lifetime.Post.Total.Reach", label = "Post Total Reach")
In conclusion, what shall I do to plot only the two desired series ("Lifetime.Engaged.Users" & "Lifetime.Post.Total.Reach"), without having to create 33 xts dataframes ?

Stacked bar in R

I have a table exported in csv from PostgreSQL and I'd like to create a stacked bar graph in R. It's my first project in R.
Here's my data and what I want to do:
It the quality of the feeder bus service for a certain provider in the area. For each user of the train, we assign a service quality based of synchronization between the bus and the train at the train stations and calculate the percentage of user that have a ideal or very good service, a correct service, a deficient service or no service at all (linked to that question in gis.stackexchange)
So, It's like to use my first column as my x-axis labels and my headers as my categories. The data is already normalized to 100% for each row.
In Excel, it's a couple of clicks and I wouldn't mind typing a couple of line of codes since it's the final result of an already quite long plpgsql script... I'd prefer to continue to code instead of moving to Excel (I also have dozens of those to do).
So, I tried to create a stacked bar using the examples in Nathan Yau's "Visualize This" and the book "R in Action" and wasn't quite successful. Normally, their examples use data that they aggregate with R and use that. Mine is already aggregated.
So, I've finally come up with something that works in R:
but I had to transform my data quite a bit:
I had to transpose my table and remove my now-row (ex-column) identifier.
Here's my code:
# load libraries
library(ggplot2)
library(reshape2)
# load data
stl <- read.csv("D:/TEMP/rabat/_stl_rabattement_stats_mtl.csv", sep=";", header=TRUE)
# reshape for plotting
stl_matrix <- as.matrix(stl)
# make a quick plot
barplot(stl_matrix, border=NA, space=0.1, ylim=c(0, 100), xlab="Trains", ylab="%",
main="Qualité du rabattement, STL", las = 3)
Is there any way that I could use my original csv and have the same result?
I'm a little lost here...
Thanks!!!!
Try the ggplot2 and reshape library. You should be able to get the chart you want with
stl$train_order <- as.numeric(rownames(stl))
stl.r <- melt(stl, id.vars = c("train_no", "train_order"))
stl.r$train_no <- factor(
stl.r$train_no,
levels = stl$train_no[order(stl$train_order)])
ggplot(stl.r, aes(x = factor(train_no), y = value, fill = variable)) + geom_bar(stat = 'identity')
It appears that you transposed the matrix manually. This can be done in R with the t() function.
Add the following line after the as.matrix(stl) line:
stl_matrix <- t(stl_matrix)

Resources