Plotly code - viewer graph doesn't showup - r

I am running the example code for the Slider function (example 2) in R:https://plot.ly/r/animations/
I want to simply reproduce the given example.
However, the graph doesn't show up in my viewer.
This is the codeI run in R:
library(plotly)
library(gapminder)
p <- gapminder %>%
plot_ly(
x = ~gdpPercap,
y = ~lifeExp,
size = ~pop,
color = ~continent,
frame = ~year,
text = ~country,
hoverinfo = "text",
type = 'scatter',
mode = 'markers'
) %>%
layout(
xaxis = list(
type = "log"
)
)
I didn't change it from the way it is described here.
Can one help me and tell me why the graph doesn't show up?

I tried to run the code at start without success as well.
Basically the issue was :
Evaluation error: `as_dictionary()` is defunct as of rlang 0.3.0 Please use `as_data_pronoun()` instead.
I think you just need to update your dplyr to the latest version 0.7.7.
install.packages("dplyr") #or update current version
Also check that :
Any package larger than a few Kb gives the message:
Warning in install.packages :
unable to move temporary installation ‘C:\Users[myname]\R\win-library\3.4\file2b884fc37c13\packagename’ to ‘C:\Users[myname]\R\win-library\3.4\packagename’
If so,Type in : trace(utils:::unpackPkgZip,edit = T)
and edited Line 140 Sys.sleep(0.5) to Sys.sleep(2).
Then you can Run your code and print p
Check out the plot
btw a real cool one !

Related

Animating Histograms with plotly

I'm trying to create an animated demonstration of the Law of Large Numbers, where I want to show the histogram converging to the density as the sample size increase.
I can do this with R shiny, putting a slider on the sample size, but when I try to set up a plotly animation using the sample size as the frame, I get an error deep in the bowels of ggploty. Here is the sample code:
library(tidyverse)
library(plotly)
XXX <- rnorm(200)
plotdat <- bind_rows(lapply(25:200, function(i) data.frame(x=XXX[1:i],f=i)))
hplot <- ggplot(plotdat,aes(x,frame=f)) + geom_histogram(binwidth=.25)
ggplotly(hplot)
The last line returns the error. Error in -data$group : invalid argument to unary operator.
I'm not sure where it is suppose to be getting data$group (this value has been magically set for me in other invocations of ggplotly).
Skipping the initial ggplot and going straight to plotly, does this work for you?
plotdat %>%
plot_ly(x=~x,
type = 'histogram',
frame = ~f) %>%
layout(yaxis = list(range = c(0,50)))
Or, using your original syntax, we can add a position specification that seems to prevent the bug. This version looks better, with standard ggplot formatting and tweened animation.
hplot <- ggplot(plotdat, aes(x, frame = f)) +
geom_histogram(binwidth=.25, position = "identity")
ggplotly(hplot) %>%
animation_opts(frame = 100) # minimum ms per frame to control speed
(I don't know why this fixes it, but when I googled your error I saw a plotly issue on github that was solved by specifying the position, and it seems to fix the error here too. https://github.com/plotly/plotly.R/issues/1544)

How to use a custom marker symbol in plotly scattermapbox for R

I am currently developing a small shiny application that uses an interactive map. The idea is very simple: I am trying to plot a handful of points in a map using lat/long coordinates. I cannot use google's API, so I used plotly's scatter plot, specifying a map layout.
This is a generic representation of what I have so far:
fig <- plotly::plot_ly(
data = data,
lat = data$lat,
lon = data$long,
mode = "markers",
marker = list(size = 10),
type = 'scattermapbox',
hovertext = paste0(
paste0("Some info 1: ", data$field1, "\n"),
paste0("Some info 2: ", data$field2, "\n"),
paste0("Some info 3: ", data$field3)
)
)
# specify layout as open street map
fig <- fig %>%
layout(
mapbox = list(
style = 'open-street-map',
zoom = 3,
center = list(lat = -20.72623, lon = -47.74942))
)
print(fig)
Considering that my "data" dataset has the fields and coordinates, the result I'm getting is this:
What I am not able to do is change the marker symbols. According to plotly's documentation (https://plotly.com/r/reference/#scatter-mode), it is as simple as defining symbol = "some_symbol", but that won't work. I've seen some examples and some workarounds, but none seem to work very intuitively.
Ideally, I wanted to generate a map that looked like this:
Does anyone know if this is even possible with a simple scatterplot? Is there any other way? Am I missing something here?
I found a solution for this, although using a different package.
Using the leaflet package, I was able to create a map using the same open-street-map layout. The default marker symbol/icon is a pin, but you can create any customized icon you want, using svg files. The leaflet documentation is specified
here.
My specific solution was defining the hovertext as a set of labels and then simply calling the addMarkers function inside the leaflet object.
labels <- lapply(seq(nrow(data)), function(i) {
paste0( '<p><b> Some information: ', data[i, "field1"], '</b></p>',
"<p> Some other information : ", data[i, "field2"] / 1000, ' MWm </p>',
"<p> Some different information : ", data[i, "field3"],'</p>')
})
fig <- leaflet::leaflet(data = data) %>% leaflet::addTiles() %>%
leaflet::addMarkers(
~as.numeric(longitude),
~as.numeric(latitude),
label = lapply(labels, htmltools::HTML)
)
print(fig)

Enabling autoscale by default on a ggplotly object

I have converted several ggplot2 objects to plotly via the ggplotly command.
After the plot renders, and I publish to my Shiny server, I need to manually click "Autoscale" on the plot before it will autoscale. I want it to use this behaviour by default. I'm unsure exactly how to get the argument in there, and whether it is possible.
My current code
library(ggplot2)
library(plotly)
plot1 <- ggplot(my_data, aes(x=month, y=views, colour=category)) + geom_line(size = 1)
ggplotly(plot1)
I'm unsure of the argument required, and cannot find documentation on how to exactly achieve this. Is anybody able to assist?
The comments to your post point you in an appropriate direction, but the example there is slightly different because it does not involve calling ggplotly on a ggplot object. As it turns out, you can just pipe the layout argument:
ggplotly(plot1) %>%
layout(xaxis = list(autorange = TRUE), yaxis = list(autorange = TRUE))

Plotly - unused arguments error - appears inconsistent

I am creating a Rmarkdown document that contains a number of plots created with plotly.
I cannot figure out why one of my plots is throwing an 'unused arguments' error, as the plot I create before it, which using the same arguments but a different subset of data, works fine. I want to use these 2 plots in a subplot.
Here's what I've got:
df_subset1_p <-
plot_ly(df_subset1, x = ~Month, y = ~data.percent, width = 800, height = 500) %>%
add_lines(color = ~cat) %>%
layout(xaxis = x, yaxis = y, margin = m)
df_subset2_p <-
plotly(df_subset2, x = ~Month, y = ~data.percent, width = 800, height = 500) %>%
add_lines(color = ~cat) %>%
layout(xaxis = x, yaxis = y, margin = m)
Before I can even call the subplot, df_subset2_p throws the error:
Error in plotly(df_subset2, x = ~Month, y = ~data.percent, : unused arguments (x = ~Month, y = ~data.percent, width = 800, height = 500)
I get the error on the 2nd plot, even if I try to run it first. The error reproduces if I just run the script and not the RMarkdown.
The structure of the dataframes looks fine to me. Month is a factor and data.percent is numeric for both.
I tried removing width, height and layout options, same error.
The error reproduces if I run the script without Rmarkdown.
I haven't found this exact problem reported by others on SO, though there are some similar complaints suggesting a compatibility issue between plotly and ggplot (older versions) or that another loaded package is using the same function name. But I don't see how this can be the case here, since I have many previous plots in the notebook that work fine.
df_subset2_p <-
plotly([...])
should be:
df_subset2_p <-
plot_ly([...])
Edit:
See ?plotly and ?plot_ly
The error was all in the typo. (Sighs.)
plot_ly initiates a plotly visualization, whereas plotly is a deprecated function previously used to store plotly account credentials.
Always use plot_ly.

Error Msgs After Package Updates for My Dashboard Outputs

I just installed a bunch of new package updates this morning (including plotly, dygraphs, rCharts, shiny and shinydashboard), and suddenly almost all outputs on my dashboard that I worked months on are broken, while they worked yesterday without a problem! For most charts I get the following error:
ERROR: object of type 'closure' is not subsettable
This is for plotly graphs like this one:
ui:
plotlyOutput("Top10Events")
server:
output$Top10Events <- renderPlotly({
x <- list(
title = " "
)
y <- list(
title = "Total Events"
)
plot_ly(x = Top10$event,
y = Top10$totalEvents.x,
type = "bar",
color = Top10$totalEvents.x,
name = "This Month",
marker = list(color = brewer.pal(10, "Paired"))) %>%
layout(xaxis = x, yaxis = y, autosize = F, width = 700, height = 350, margin = m)
p2 <- add_trace(
p,
x = Top10$event,
y = Top10$totalEvents.y,
name = "Last Month",
type = "bar",
color = Top10$totalEvents.y,
marker = list(color = brewer.pal(10, "Paired")))
})
I read that this error occurs mostly when {} are missing for reactive values, but as everything just worked fine yesterday I don't think this is the issue.
I figured it is likely a shiny issue? So I installed the old version of Shiny (0.13.2) successfully, but get a new error:
Error in get(Info[i, 1], envir = env) :
lazy-load database 'C:/Users/user/Documents/R/R-
3.3.1/library/shiny/R/shiny.rdb' is corrupt
In addition: Warning message:
In get(Info[i, 1], envir = env) : internal error -3 in R_decompress1
Tried it with an older shinydashbaord version as well (0.5.2), but I get the following error when installing:
The following object is masked from ‘package:graphics’:
box
My version of R & RStudio is also the newest apparently.
Any suggestions on how to approach the debugging process further and save my dashboard?
Many thanks, any help is appreciated!
EDIT:
The latest oldest plotly version I can find on https://cran.r-project.org/src/contrib/Archive/plotly/ is only plotly_3.6.0, while I am currently running 4.5.2 (as I figured it might be a plotly issue).
Trying to install the 3.6.0 version, I get again the following error:
The following object is masked from ‘package:igraph’:
%>%
The following object is masked from ‘package:ggplot2’:
last_plot
The following object is masked from ‘package:graphics’:
layout
EDIT 2: Sorry for all the edits - so now I managed to upload the old plotly package, 3.6.0, and everything works again. Seems like the new package is either full of bugs, or I need to code my graphs differently? I could not find any helpful resource on that. Could anyone help?
I think that the new packages you install have objects of the same name of your old packages, thereby "overwriting" your old objects. You could try accessing your masked objects by using graphics::layout() instead of layout().
Edit: Look here for more information.

Resources