dygraphs in R markdown tabsets not loaded properly - r

I am making multiple dygraphs in a R markdown document. Each dygraph should be in it's own tabset. The code for one of my dygraphs is the following:
# Make a dygraph
dygraph(xts_data, main = "Totaal van nieuwe tickets") %>%
dyRangeSelector() %>%
dyHighlight(highlightCircleSize = 5,
highlightSeriesBackgroundAlpha = 0.2,
hideOnMouseOut = TRUE) %>%
dyLegend(width = 600) %>%
dyOptions(colors = RColorBrewer::brewer.pal(4, "Dark2")[c(1,3,4)],
fillGraph = TRUE, fillAlpha = 0.4)
This code is properly put within a tabset which is created through the following code:
## Ticket data {.tabset .tabset-fade .tabset-pills}
Now what seems to have is that each time I open a new tab, it doesn't properly display the dygraph. Only when I resize the compiled html document, the graph becomes properly visible again. Has anyone had a similar experience and knows how to solve this?

Related

Change output width of plotly chart size in R Markdown PDF output

On a R markdown file, does someone know why out.width,out.height,figure.width and figure.height parameters doesn't change plotly charts size when producing a pdf file? ( I precise that such parameters works perfectly using plot function)
Please find below a reproductible example with a Rmarkdown file
On this example, I would like the plotly chart to occupy the entire sheet like the plot chart.
---
title: "Change chart size chart on pdf file using plotly"
output:
pdf_document: default
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(echo=FALSE,message=FALSE)
```
## Parameters doesn't work with plotly
```{r, out.width='100%',out.height='100%',fig.height=20, fig.width=15, fig.align="left"}
library(plotly)
plot_ly(x = cars[1:10,]$speed,y = cars[1:10,]$dist)
```
## Parameters works using plot function
```{r,out.width='130%',out.height='100%', fig.height=20, fig.width=15, fig.align="left"}
plot(cars[1:10,])
```
Plotly graphs are primarily designed for interactive outputs, and as such, can behave a bit strange when being exported to static images in PDF. This issue has had some similar posts in the past, and appears to come from how webshot creates the static image.
You can fix this by forcing the plotly graph dimensions when creating the graph. The plot_ly function has the arguments width and height which let you set the output dimensions of the resulting plot.
If you want to include HTML objects in PDF reports, you can use the webshot package which essentially takes a screenshot of the rendered plots and converts it into a static image for you to include in the report. This is explained well in the bookdown book. To install it, you will need to run:
install.packages('webshot')
webshot::install_phantomjs()
Once webshot is installed, it should work automatically:
---
title: "Change chart size chart on pdf file using plotly"
output:
pdf_document: default
papersize: a4
---
```{r include=FALSE}
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE)
library(plotly)
```
```{r, out.width="100%"}
plot_ly(x = cars[1:10,]$speed,y = cars[1:10,]$dist, width = 1000, height = 1200)
```
Will update this answer if I can work out exactly why it works, but hope that helps!
You need to be very careful while working with plotly graphs with r markdown pdf.
While creating the plotly graph,
Don't forget to explicitly set the size (width and height) of the graph
Use the chunk option of out.width and out.height. They both accept pt,mm,in,px,%
If you're producing the latex output in the pdf then 'px' will not work.
Please find the below code for the graph and the output of the same.
f <- list(
size = 30,
family = 'sans-serif'
)
m <- list(
l = 100,
r = 50,
b = 0,
t = 0,
pad = 4
)
p <- plot_ly(width = 800, height = 800) %>%
add_markers(data = pressure, x = pressure$temperature, y = pressure$pressure) %>%
layout(font = f, margin = m)
p
The output produced by this is
with size and margins
Now after modifying the code chunk options as below:
```{r pressure2, echo=FALSE, out.height="150%", out.width="150%"}
f <- list(
size = 30,
family = 'sans-serif'
)
m <- list(
l = 100,
r = 50,
b = 0,
t = 0,
pad = 4
)
p <- plot_ly(width = 800, height = 800) %>%
add_markers(data = pressure, x = pressure$temperature, y = pressure$pressure) %>%
layout(font = f, margin = m)
p
```
you will get a much bigger graph
Keep coding!
Have you tried only using fig.height & fig.width options and remove out.width and out.height?
{r , fig.height=6, fig.width=9.5}
I am playing around with plotly and I've had success using HTML notebooks using this. It's a little more trial and error but you don't have to rebuild the plots.

R crashes when trying to add a plot on a powerpoint template

I have developed a dashboard using R and the library shiny, where some different charts are displayed. These ones aren't static charts but they are generated dynamically according to some filters you can set through some bottons and so on.
The next step, what I am working on right now it would be to create a powerpoint report including those charts I have generated before. I got this piece of code so far:
report <- pptx(template = 'report_template.pptx')
report <- addSlide(report,"report_layout")
slide.layouts(report)
slide.layouts(report, "report_layout")
report <- addPlot(report, function() print(p))
writeDoc(report, "example_report.pptx")
Being p a given chart created by plotly this way:
p <- plot_ly(agregado_cedex(), labels = ~Escalado, values = ~Total,type = "pie",
text = ~Total, width = 500, height = 250, hoverinfo = "none") %>% config(displayModeBar = FALSE) %>%
layout(title = "Desglose incidencias", showlegend = TRUE,
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
There is no problem with this chart as it is correctly displayed on the shiny app (dashboard).
When executing the code above I am getting the next error on R Studio:
Warning: Error in .jcall: javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException: The markup in the document preceding the root element must be well-formed.]
I found something a similar post but it haven't been solved so far Add plots in PPTx without crashing R using addplot()
Does anyone know what is wrong? Thanks in advance!
ReporteRs does not support htmlwidgets. addPlot work with base plot commands, ggplot2, grid and lattice.

Reproducing a Choropleth Map by using plotly package in R

library(plotly)
df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv")
df$hover <- with(df, paste(state, '<br>', "Beef", beef, "Dairy", dairy, "<br>",
"Fruits", total.fruits, "Veggies", total.veggies,
"<br>", "Wheat", wheat, "Corn", corn))
# give state boundaries a white border
l <- list(color = toRGB("white"), width = 2)
# specify some map projection/options
g <- list(
scope = 'usa',
projection = list(type = 'albers usa'),
showlakes = TRUE,
lakecolor = toRGB('white')
)
p <- plot_geo(df, locationmode = 'USA-states') %>%
add_trace(
z = ~total.exports, text = ~hover, locations = ~code,
color = ~total.exports, colors = 'Purples'
) %>%
colorbar(title = "Millions USD") %>%
layout(
title = '2011 US Agriculture Exports by State<br>(Hover for breakdown)',
geo = g
)
p
The above code is from plotly website and the plot produced should be as follows:
However, the plot I generated by using the code is as follows:
What happens? Do I need to install some other packages to reproduce the correct plot?
I got this too. If you open the javascript console you can see an error:
Failed to load resource: Unable to init SSL Context:
while it is trying to open this file:
"https://cdn.plot.ly/world_110m.json"
Here is a screen shot:
Cause:
I believe this is because the non-professional Version of R-Studio does not support https by design, so there is probably no work around except wrapping it as markdown and viewing it in a browser as I describe below.
Workaround:
If you package it in R-markdown (put your code between the following lines):
```{r}
(your code here)
```
and then save it as an .Rmd file) and knit it. Then it will still not work in the R-Studio preview-browser, and but it does if you use the "Open in Browser" function and open it in Chrome (for example).
Or buy the professional version :).

plotting barchart in popup using leaflet library

Quick question all.
I have some data in sql server which i have loaded into RStudio. I have made a barchart for the data and now i am using leaflet library with the use of latitude and longitude to plot a point on the map. I want to be able to use popup to show a barchart in it when the user clicks on the point.
BarChart code (maybe this is a problem because i am using googleVis library so not sure if i can use this in the popup. but again this is the most appropriate bar graph i can make and need- other suggestions could be helpful as i am not a professional in R libraries yet)
Switzerland <- sqlQuery(con, "sql query")
SwitzerlandChart <- gvisBarChart(Switzerland, options = list(height=200))
For the graph plot the code is:
m <- leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addCircles(lng=8.498868, lat=46.9221, popup=paste(plot(SwitzerlandChart)))
When i run this code it opens a webpage to view my barplot.
Then i run the following:
m #Prints the graph
This prints the graph with the point in the desired location but the popup shows me a webpage instead which also only i can open.
I want to be able to plot the bargraph inside the popup please.
Hope someone can help
Maybe a little late but here's a solution. The addPopups() function in library(leaflet) seems to be able to handle .svg files. Therefore, you could simply save your plot using svg() and then read it again using readLines(). Here's a reproducible example using library(mapview):
library(lattice)
library(mapview)
library(sp)
data(meuse)
coordinates(meuse) <- ~x+y
proj4string(meuse) <- CRS("+init=epsg:28992")
clr <- rep("grey", length(meuse))
fldr <- tempfile()
dir.create(fldr)
pop <- lapply(seq(length(meuse)), function(i) {
clr[i] <- "red"
p <- xyplot(meuse$cadmium ~ meuse$copper,
col = clr, pch = 20, alpha = 0.7)
svg(filename = paste(fldr, "test.svg", sep = "/"),
width = 250 * 0.01334, height = 250 * 0.01334)
print(p)
dev.off()
tst <- paste(readLines(paste(fldr, "test.svg", sep = "/")), collapse = "")
return(tst)
})
mapview(meuse, popup = pop, cex = "cadmium")
You will see that each popup is a scatterplot. As for a leaflet example, consider this:
content <- pop[[1]]
leaflet() %>% addTiles() %>%
addPopups(-122.327298, 47.597131, content,
options = popupOptions(closeButton = FALSE)
)
In case you need the plot to be interactive, you could have a look at library(gridSVG) which is able to produce interactive svg plots from e.g. lattice or ggplot2 plots.
UPDATE:
library(mapview) now has designated functionality for this:
popupGraph: to embed lattice, ggplot2 or interactive hatmlwidgets based plots.
popupImage: to embed local or remote (web) images
This is currently only available in the development version of mapview which can be installed with:
devtools::install_github("environmentalinformatics-marburg/mapview", ref = "develop"
This may be a little late too, but here is a full leaflet implementation. I first create the plot and then use the popupGraph function to add it in.
# make a plot of the two columns in the dataset
p <- xyplot(Home ~ Auto, data = Jun, col = "orange", pch = 20, cex = 2)
# make one for each data point
p <- mget(rep("p", length(Jun)))
# color code it so that the corresponding points are dark green
clr <- rep("orange", length(Jun))
p <- lapply(1:length(p), function(i) {
clr[i] <- "dark green"
update(p[[i]], col = clr)
})
# now make the leaflet map
m1 <- leaflet() %>%
addTiles() %>%
setView(lng = -72, lat = 41, zoom = 8) %>%
# add the markers for the Jun dataset
# use the popupGraph function
addCircleMarkers(data = Jun, lat = ~Lat, lng = ~Lon,
color = ~beatCol(BeatHomeLvl), popup = popupGraph(p),
radius = ~sqrt(BeatHome*50), group = 'Home - Jun') %>%
# layer control
addLayersControl(
overlayGroups = c('Home - Jun'
),
options = layersControlOptions(collapsed = F)
) %>%
# legend for compare to average
addLegend('bottomright', pal = beatCol, values = last$BeatTotalLvl,
title = 'Compare<br>Quote Count to<br>3Mos State Avg',
opacity = 1)
m1
Here is the output.

Can I include tooltips in the d3pie rcharts implementation?

I am creating a d3pie graph with rcharts following this article.
I am able to create the pie chart and now I would like to add a tooltip similar to this one.
My code so far is:
require(magrittr)
require(dplyr)
require(rCharts)
df<-data.frame(label=c("group1","group2","group3"),value=c(1,5,4),
stringsAsFactors = FALSE)
pie1<-rCharts$new()
pie1$setLib("http://timelyportfolio.github.io/rChartsExtra/d3pie")
pie1$params$chartspec <- list(header = list(title = list(text = "Title"),
subtitle = list(text = "Subtitle")),
data = list(content = df),
labels = list(lines = list(style = "straight")),
tooltips=list(enabled=TRUE,type= "placeholder",
string="{label}"))
pie1
I am not sure if including the tooltips is possible with rcharts.
If it is possible my guess is that the problem comes from the enabled=TRUE. I also tried: enabled="[true]", enabled="{true}" and enabled=T. None of them seem to work.
I am starting to learn d3.js, however, I want to embed the chart in rmarkdown so I would prefer a solution based on R.

Resources