R plot_ly hoverinfo - r

I'm using plot_ly in a shiny app. I've the following function
plot_ly(df, x = ~x, y = ~y , key = df$id, type='scatter', mode="markers",
name = "Clusters", opacity = point.opacity, text = df$id, hoverinfo = "text")
If the length of df$id is not 0 then everything is fine. If the length is 0 because no data is available I get the following error: Error in : Column 'hoverinfo' must be length 0, not 1. If I omit hoverinfo, then everything is fine with the empty dataset.
How can I fix this? I tried to use ifelse but that doesn't work. My solution is to define a if statement and then call plot_ly with or without hoverinfo. Does anybody have an better idea?

Related

Change colors for NA values to gray in R plotly scatter 3d

I'm trying to generate a plot in which I want to show NA values in translucent gray, and a set of numeric values I want to plot with a blue-red color scale. By default, plotly colors my NAs with a dark gray solid color, but I figure there must be a way to change that somehow. Is there anyway to do it? Here is a mockup of my code:
library("plotly")
blue_red <- rev(c("#A50026", "#D73027", "#F46443", "#FDAE61", "#FEE090"
, "#E0F3F8", "#ABD9E9", "#74ADD1", "#4575B4", "#313695"))
mtcars$brand <- sapply(strsplit(rownames(mtcars), " "), "[[", 1)
mtcars[mtcars$brand=="Merc","mpg"] <- NA
fig <- plot_ly(mtcars, x = ~wt, y = ~hp, z = ~qsec,
marker = list(size = 6),
color=~mpg,
colors = blue_red,
type = "scatter3d",
mode = "markers")
fig
I found a somewhat similar question here: https://community.plotly.com/t/how-to-change-colors-for-na-values-to-gray-in-a-choropleth-map/15746/3 but I haven't been able to translate that to solve my problem.
Edited to make sense OK, so you have known triplets for x,y,z coordinates and you want to assign colors to various values of mpg. Can you simply do the following?
mtcars[mtcars$brand=="Merc","mpg"] <- your_chosen_value and assign a desired color to that value.
If that distorts the colors mapped to numeric values that are genuine, maybe it's simpler to plot all the non-"Merc" data with one call and then plot all the "Merc" data with a second call that uses a simple, single-value color assignment instead of your blue_red vector.

R: 1 Dimensional "scatterplot"

I am using the R programing language. Recently, I came across this previous stackoverflow post where it describes how to make a 1 dimensional scatter plot in R: How can I plot a 1-D plot in R?:
x <- rnorm(100,10,10)
x <- data.frame(x,1) ## 1 is your "height"
plot(x, type = 'o', pch = '|', ylab = '')
My question: is it possible to transform the above plot into a "plotly" plot?
Suppose I have the following data:
library(plotly)
x <- rnorm(100,10,10)
color <- rnorm(100, 2,1)
frame = data.frame(x,color)
Would it be possible to do something like this?
fig <- plot_ly(data = frame, x = ~frame$x, color ~ frame$color )
fig
I get the following error when running this code:
No trace type specified:
Based on info supplied, a 'histogram' trace seems appropriate.
Can someone please show me how to do this?
Thanks
Source: https://plotly.com/r/line-and-scatter/
In plotly language, a trace is the type of visualization that you would like to use to display your data. So the error basically lets you know that you have not specified any trace and that the program is picking one for you: "a histogram". For scatterplots, you need type = "scatter" and mode = "markers'.
Also, inside the plot_ly() function, once you specify the data argument, you can simply access the columns with the column name preceded by a tilde ~.
Finally, since you want a one dimensional scatterplot along the x-axis, you need to add y = " " to the plot_ly() function.
This is how you can achieve your desired result:
library(plotly)
x <- rnorm(100,10,10)
color <- rnorm(100, 2,1)
frame = data.frame(x,color)
plot_ly(type = "scatter", mode = "markers", data = frame, x = ~x, y = " ", color = ~color )
Note that plotly is a very rich framework and you can read the appropriate documentation to learn how to customize your plot to your liking.

R multiple lines plotly chart with customized line types

I have probably a simple R plotly question but I spent about one hour reading questions in stackoverflow and I really can't find what I need. I have a dataframe (I will share a screenshot) with different columns used to create a multiple lines plotly chart.
This is the code I use to create the plot:
plot_ly(data = df_final, x=~TENOR, y=~RATE) %>% add_trace(type='scatter',mode='lines', color=~LINE_NAME, colors = ~LINE_COL) %>%
layout(title=paste0("Market data"),
xaxis=list(title='Term (years)'),
yaxis=list(title='Yield'))
it works amazing but I would like to have the option to choose if some lines will have to be dashed, dots, or solid lines as well as their width.
I would need / want to specify this information inside the dataframe and choose the dataframe column that has such information (i.e. see the column "LINE_STYLE_FACTOR" in my attached dataframe).
I checked Multiple line chart using plotly r and Plotly r, line style by variable but I can't find how to do what I need.
The solution has to use plotly and not other charting solutions.
Thanks
At least for the line types (dash vs line), you can you 'linetype':
library(dplyr)
library(plotly)
df = data.frame(xVals = rep(1:10,2),
yVals = c(1:10, 2:11),
myColor = c(rep('Red', 10), rep('Blue', 10)),
myType = c(rep('solid', 10), rep('dot', 10)),
myName = c(rep('FirstName', 10), rep('SecondName', 10)))
plot_ly(df,
x = ~xVals,
y = ~yVals,
color = ~I(myColor),
name = ~myName,
type = 'scatter',
mode = 'lines',
linetype = ~I(myType)
)

Rows As Series Plotly R

I have a dataframe:
df<-data.frame(Level=c("Small","Bigger","Biggest"),Threshold1=c(0.9,.8,.7),Threshold2=c(0.4,.5,.6),Threshold3=c(.6,.2,.1))
I want to produce a graphic as below, but using plotly:
How would you read this in to plotly and make this happen?
I have tried rotating using t() and looked at plotly documentation, but didn't see anything about a means to use rows as series and the value of an identifier column as series name.
In my real-life data, the number of values that can exist in the Level column can change, so ideally I would like to find a solution that can scale with whatever number of values Level may consist of.
Any help is much appreciated!
It is easier if you use data.table:
library(data.table)
library(plotly
df<-data.table(Level=c("Small","Bigger","Biggest"),Threshold1=c(0.9,.8,.7),Threshold2=c(0.4,.5,.6),Threshold3=c(.6,.2,.1))
d <-melt.data.table(df, id.vars='Level')
plot_ly(d, x=~variable, y=~value,type = 'scatter', mode = 'lines', color = ~Level)
You should obtain the desired chart.
Solution in base R:
library(plotly)
df<-data.frame(Level=c("Small","Bigger","Biggest"),
Threshold1=c(0.9,.8,.7),Threshold2=c(0.4,.5,.6),Threshold3=c(.6,.2,.1))
df.reshaped <- reshape(df, varying = c("Threshold1", "Threshold2", "Threshold3"),
v.names = "Values", idvar = "Level", direction = "long",
times = c("Threshold1", "Threshold2", "Threshold3"),
new.row.names = 1:(3 * nrow(df)))
plot_ly(df.reshaped, x=~time, y=~Values, type = 'scatter', mode = 'lines', color = ~Level)
Output plot:

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.

Resources