I am trying to combine a two plotly figures (type = 'mesh3d' and type = 'scatter3d'). Each of the single plots is perfectly fine without any warning. After I use subplot a warning occurs every time I try to display the plot.
warning 'layout' objects don't have these attributes: 'NA'
I have tried to suppressWarning but this does not have any effect.
Any ideas what I am missing here to get rid of the warning?
Plotly Version: 4.9.3
R Version: 4.0.1
# plot data
plt_data <- data.frame(maturity=rep(1:10, each=10),
tenor=rep(1:10, 10),
value=rnorm(100))
# plot 1
fig11 <- plot_ly(
data=plt_data, x=~maturity, y=~tenor, z = ~value,
type = "mesh3d",intensity = ~value,
colors = colorRamp(c(
rgb(168, 191, 173, max = 255),
rgb(100, 181, 117, max = 255),
rgb(0,100,80, max = 255)
)),
contour=list(show=T, width=4, color="#fff"),
showscale = F,
scene='scene1',
lighting = list(ambient = 0.9),
hoverinfo="skip",
source="myID"
)
# plot 2
fig12 <- plot_ly(
data=plt_data, x=~maturity, y=~tenor, z = ~value,
type = "scatter3d",
mode="markers",
hovertemplate="Maturity: %{x:.f}<br>Tenor: %{y:.f}<br>Value: %{z:.4f}<extra></extra>",
marker=list(
symbol="square-open",
size=4,
color="#3d543f"
),
scene='scene1',
source="myID",showlegend=F
)
# subplot which does throw a warning
subplot(fig11, fig12)
For R and Shinyapps, to suppress warnings like this:
options(warn = -1)
There is an open issue regarding the warning. Here's a workaround to hide the warnings for this case -
function_to_hide_plotly_warning <- function(...) {
plot <- subplot(...)
plot$x$layout <- plot$x$layout[grep('NA', names(plot$x$layout), invert = TRUE)]
plot
}
function_to_hide_plotly_warning(fig11, fig12)
Related
I created an areaRange plot with the dreamRs apexcharter package and have a few issues formatting the hoverlabel/tooltip.
This is my sample code:
First, I installed the dreamRs apexcharter version using this:
#install.packages("remotes")
#remotes::install_github("dreamRs/apexcharter")
And then I loaded the following packages:
library(dplyr)
library(apexcharter)
The apexcharter version I have now is: apexcharter_0.3.1.9200
This is my example data:
test_data <- data.frame(seq(as.POSIXct('2022/09/04 22:00:00'), as.POSIXct('2022/09/08 10:00:00'), by="hour"))
test_data$MIN <- runif(n = 85, min = 70, max = 100)
test_data$MEDIAN <- runif(n = 85, min = 100, max = 120)
test_data$MAX <- runif(n = 85, min = 120, max = 150)
colnames(test_data) <- c("Date", "MIN", "MEDIAN", "MAX")
And this is my plot so far:
axc_plot <- apex(data = test_data, # plot the area range
mapping = aes(x = test_data[20:60,]$Date,
ymin = test_data[20:60,]$MIN,
ymax = rev(test_data[20:60,]$MAX)),
type = "rangeArea",
serie_name = "Vertrauensbereich") %>%
add_line(mapping = aes(x = Date, y = MEDIAN), # add the line
type = "line",
serie_name = "Median") %>%
ax_colors("lightblue", "red") %>% # why is the line not red?
ax_labs(x = "Zeit [h]",
y = "Q [m³/s]") %>%
ax_tooltip(enabled = T,
shared = T, # I want it shared but it's not
x = list(format = "dd.MM. HH:mm"), # changes grey hoverlabel at the bottom -> works
y = list(formatter = JS("function(seriesName) {return seriesName;}"), # instead of the time I want it to say "Median" and "Vertrauensbereich"
title = list(formatter = JS("function(test_data$Date) {return test_data$Date;}")))) # the title of the hoverlabel should be the time in the format "yyyy-MM-dd HH:mm:ss"
axc_plot
Here's how it looks:
rangeArea Plot with tooltip
As you can see the data in the tooltip is not displayed very well, so I want to format it using ax_tooltip but that hasn't worked very well so far. I found out that using x = will change the grey hoverlabel at the bottom of the plot and y = changes the label that runs along with the lines (which is the one I want to change). I tried to make a custom tooltip using formatter = but I don't really know how to work with it because all examples I see are made with Java Script and I don't know how to implement that in R. In ax_tooltip(y = ...) you can see how I tried to change the format using JS() because I saw it once somewhere (can't find the link anymore sadly) but I'm pretty sure that's not the way to do it as it doesn't change anything.
In the end, I'd like to achieve a tooltip that looks something like this with the Date at the top (as title) in the format "yyyy-MM-dd HH:mm:ss" if possible and then the series names with the corresponding values and hopefully also with the unit m³/s:
apex desired tooltip
Thanks in advance for any answers. I'm looking forward to hearing your suggestions!
I also asked this question on GitHub where pvictor solved my problem perfectly. This is what they answered and what works for me:
library(htmltools)
test_data <- data.frame(seq(as.POSIXct('2022/09/04 22:00:00'), as.POSIXct('2022/09/08 10:00:00'), by="hour"))
test_data$MIN <- runif(n = 85, min = 70, max = 100)
test_data$MEDIAN <- runif(n = 85, min = 100, max = 120)
test_data$MAX <- runif(n = 85, min = 120, max = 150)
colnames(test_data) <- c("Date", "MIN", "MEDIAN", "MAX")
# explicit NA if not used in area range
test_data$MIN[-c(20:60)] <- NA
test_data$MAX[-c(20:60)] <- NA
# Construct tooltip with HTML tags
test_data$tooltip <- unlist(lapply(
X = seq_len(nrow(test_data)),
FUN = function(i) {
d <- test_data[i, ]
doRenderTags(tags$div(
style = css(padding = "5px 10px;", border = "1px solid #FFF", borderRadius = "5px"),
format(d$Date, format = "%Y/%m/%d %H:%M"),
tags$br(),
tags$span("Q Median:", tags$b(round(d$MEDIAN), "m\u00b3/s")),
if (!is.na(d$MIN)) {
tagList(
tags$br(),
tags$span("Vertrauensbereich:", tags$b(round(d$MIN), "m\u00b3/s -", round(d$MAX), "m\u00b3/s"))
)
}
))
}
))
axc_plot <- apex(
data = test_data[20:60, ], # plot the area range
mapping = aes(
x = Date,
ymin = MIN,
ymax = rev(MAX),
tooltip = tooltip # variable containing the HTML tooltip
),
type = "rangeArea",
serie_name = "Vertrauensbereich"
) %>%
add_line(
data = test_data,
mapping = aes(x = Date, y = MEDIAN, tooltip = tooltip), # use same tooltip variable
type = "line",
serie_name = "Median"
) %>%
ax_colors(c("lightblue", "#FF0000")) %>% # use HEX code instaed of name
ax_theme(mode = "dark") %>%
ax_labs(
x = "Zeit [h]",
y = "Q [m³/s]"
) %>%
ax_tooltip(
# Custom tooltip: retrieve the HTML tooltip defined in data
custom = JS(
"function({series, seriesIndex, dataPointIndex, w}) {",
"var tooltip = w.config.series[seriesIndex].data[dataPointIndex].tooltip;",
"return typeof tooltip == 'undefined' ? null : tooltip;",
"}"
)
)
axc_plot
You can find the GitHub entry here: https://github.com/dreamRs/apexcharter/issues/62
I’m trying to display error bars on a scatter plot with Shiny and plotly. Here’s my code in my server.R file:
data = reactiveVal()
observe({
results <- data.frame() # actually getting the data from here
# formatting output
final.results <- cbind(
"id" = paste(results$a,
results$b,
results$c,
sep = '-'),
"sigma" = sprintf("%.5g", results$s),
"c-e" = sprintf("%.3g",results$calc - results$exp)
)
data(final.results)
})
output$plot <- renderPlotly(
as.data.frame(data()[,c("id", "c-e", "sigma")]) %>% plot_ly(
x = ~`c-e`,
y = ~id,
height = 800,
type = 'scatter',
mode = 'markers',
marker = list(color = "#90AFD9"),
error_x = list(array = ~sigma, color = "#000000", type = "data")
)
)
The plot is ok except it’s not showing the error bars, what’s my mistake ?
EDIT: clarification for the origin of the data() function and what it’s return value is.
Thesprintf() function returns a character string, not a number, that is why it is not displaying the sigma values as error bars. If you want to keep 5 decimal places, use the round() function instead:
"sigma" = round(results$s, digits = 5)
I want to plot a animated 3D scatterplot and save it as gif. I followed the code provided by the R Graph Gallery example: https://www.r-graph-gallery.com/3-r-animated-cube.html.
library(rgl)
library(magick)
options(rgl.printRglwidget = TRUE)
# Let's use the iris dataset
# iris
# This is ugly
colors <- c("royalblue1", "darkcyan", "oldlace")
iris$color <- colors[ as.numeric( as.factor(iris$Species) ) ]
# Static chart
plot3d( iris[,1], iris[,2], iris[,3], col = iris$color, type = "s", radius = .2 )
# We can indicate the axis and the rotation velocity
play3d( spin3d( axis = c(0, 0, 1), rpm = 20,dev = cur3d()),startTime = 0, duration = 10 )
# Save like gif
movie3d(
movie="3dAnimatedScatterplot",
spin3d( axis = c(0, 0, 1), rpm = 20,dev = cur3d()),
startTime = 0,
duration = 10,
dir = ".",
type = "gif",
clean = T,
fps=10,
convert=T
)
plot3d was successed output a 3d scatter plot.
Static 3d scatter plot
But the final output: 3dAnimatedScatterplot.gif,just a black image
3dAnimatedScatterplot.gif
when I set clean=F, all frame images are black. So, I guess the play3d() was not working.
Can anyone provide any help to me ? Thanks a lot !
Most likely snapshot3d isn't working for you. Try it with the option webshot = FALSE instead of the default webshot = TRUE. That uses a different mechanism for saving the image.
I'm trying to generate a circos plot with a simple genomic notation from BED files. However, when I use circos.genomeRect this results in an error, or in a track that does not plot rectangles, but semicircles as I show below.
Consider the following reproducible example:
library("circlize")
library("tidyverse")
circos.par(start.degree = 90,
cell.padding = c(0, 0, 0, 0),
#points.overflow.warning=FALSE,
track.height = 0.10
)
# Initialize genome (bed file with genome sizes)
genome <- tibble(chr=c("chr1","chr2"), start = c(1,1), end = c(6000000, 3000000))
circos.genomicInitialize(genome, plotType = c("axis"), major.by = 1000000)
# Add track with annotation
feature <- tibble(chr = c("chr1", "chr1"), start = c(2500, 4500000), end = c(4150000, 6350000))
circos.genomicTrack(feature, ylim=c(0,1),
panel.fun = function(region, value, ...) {
circos.genomicRect(region, value, ytop.column = 1, ybottom = 0, col="blue")
})
circos.clear()
This returns an error:
Error in if (sum(l) && circos.par("points.overflow.warning")) { :
missing value where TRUE/FALSE needed
In addition: Warning message:
In is.na(x) | is.na(y) :
Error in if (sum(l) && circos.par("points.overflow.warning")) { :
missing value where TRUE/FALSE needed
At this point, if points.overflow.warning=FALSE is set in circos.par above, the error disappears, but some other error must be occurring, that this does not plot rectangles:
Am I missing something? what is wrong with this simple example? Thank you
EDIT
I just noticed that the feature dataframe I plot has one coordinate wrong, since it extends longer than the actual size of the chromosome. However, if this is fixed, eg: feature <- tibble(chr = c("chr1", "chr1"), start = c(2500, 4500000), end = c(4150000, 5350000)), a new error appears!!
Warning message:
In is.na(x) | is.na(y) :
longer object length is not a multiple of shorter object length
It seems to work with data.frames instead of tibbles:
library("circlize")
circos.par(start.degree = 90,
cell.padding = c(0, 0, 0, 0),
#points.overflow.warning=FALSE,
track.height = 0.10
)
# Initialize genome (bed file with genome sizes)
genome <- data.frame(chr=c("chr1","chr2"), start = c(1,1), end = c(6000000, 3000000))
circos.genomicInitialize(genome, plotType = c("axis"), major.by = 1000000)
# Add track with annotation
feature <- data.frame(chr = c("chr1", "chr1"), start = c(2500, 4500000), end = c(4150000, 5350000))
circos.genomicTrack(feature, ylim=c(0,1),
panel.fun = function(region, value, ...) {
circos.genomicRect(region, value, col="blue")
})
circos.clear()
Created on 2020-08-11 by the reprex package (v0.3.0)
I'm trying to get familiar with plotly's functionality and syntax and have tried several of the scripts provided to compose and render plots of data. However, when generating the plotly output using RStudio I'm getting the following error: "Warning message:
Specifying width/height in layout() is now deprecated.
Please specify in ggplotly() or plot_ly()"
The output image appears jumbled and uninterpretable in the RStudio console and I've tried a few changes like setting the plotly object's width and height equal to null etc without luck.
Here is one of the sample scripts I've used when experiencing this issue:
library(plotly)
trace1 <- list(
x = c("Aug-12", "Sep-12", "Oct-12", "Nov-12", "Dec-12", "Jan-12", "Feb-13", "Mar-13", "Apr-13", "May-13", "Jun-13", "Jul-13"),
y = c(65, 77, 112, 279, 172, 133, 152, 106, 79, 225, 99, 150),
hoverinfo = "x+y+name",
line = list(
color = "#5BC075",
width = "3"
),
mode = "lines",
name = "Median deal size",
type = "scatter",
uid = "a8e83b",
xsrc = "jackluo:508:b357d2",
ysrc = "jackluo:508:d19900"
)
trace2 <- list(
x = c("Aug-12", "Sep-12", "Oct-12", "Nov-12", "Dec-12", "Jan-12", "Feb-13", "Mar-13", "Apr-13", "May-13", "Jun-13", "Jul-13"),
y = c(116, 125, 126, 125, 244, 136, 80, 82, 89, 82, 95, 107),
hoverinfo = "x+y+name",
line = list(
color = "#CC6E55",
width = "3"
),
mode = "lines",
name = "Number of deals",
type = "scatter",
uid = "2be33b",
xsrc = "jackluo:508:b357d2",
ysrc = "jackluo:508:5d533d"
)
data <- list(trace1, trace2)
layout <- list(
autosize = TRUE,
font = list(
family = "Overpass",
size = 12
),
height = 720,
legend = list(
x = 0,
y = -0.1,
bgcolor = "rgba(255, 255, 255, 0)",
orientation = "h"
),
margin = list(
r = 40,
t = 40,
b = 40,
l = 40,
pad = 2
),
title = "",
width = 1280,
xaxis = list(
autorange = TRUE,
nticks = 12,
range = c(0, 11),
rangemode = "tozero",
type = "category"
),
yaxis = list(
autorange = TRUE,
range = c(0, 293.6842105263158),
rangemode = "tozero",
type = "linear"
)
)
p <- plot_ly()
p <- add_trace(p, x=trace1$x, y=trace1$y, hoverinfo=trace1$hoverinfo, line=trace1$line, mode=trace1$mode, name=trace1$name, type=trace1$type, uid=trace1$uid, xsrc=trace1$xsrc, ysrc=trace1$ysrc)
p <- add_trace(p, x=trace2$x, y=trace2$y, hoverinfo=trace2$hoverinfo, line=trace2$line, mode=trace2$mode, name=trace2$name, type=trace2$type, uid=trace2$uid, xsrc=trace2$xsrc, ysrc=trace2$ysrc)
p <- layout(p, autosize=layout$autosize, font=layout$font, height=layout$height, legend=layout$legend, margin=layout$margin, title=layout$title, width=layout$width, xaxis=layout$xaxis, yaxis=layout$yaxis)
p$x$layout$width <- NULL
p$x$layout$height <- NULL
p$width <- NULL
p$height <- NULL
p
Any help resolving this issue so charts are correctly scaled and legible would be much appreciated!
As #NoahOlsen suggested, you need to format your x-axis values as a date.
trace1$x <- as.Date(paste0("01-", trace1$x), format = "%d-%b-%y")
trace2$x <- as.Date(paste0("01-", trace2$x), format = "%d-%b-%y")
Explanation
as.Date() tries to format an input into a date object. It works well with ISO date strings (e.g., 2019-04-21), but needs some help with more tricky formats.
From ?strptime:
%d - Day of the month as decimal number (01–31).
%b - Abbreviated month name in the current locale on this platform. (Also matches full name on input: in some locales there are no abbreviations of names.)
%Y - Year with century. Note that whereas there was no zero in the original Gregorian calendar, ISO 8601:2004 defines it to be valid (interpreted as 1BC): see https://en.wikipedia.org/wiki/0_(year). Note that the standards also say that years before 1582 in its calendar should only be used with agreement of the parties involved. For input, only years 0:9999 are accepted.
Furthermore, we also need a specific day of the month. As it does not exist in your data, I added 01- via paste0() to every value of the date vector. Other values, such as 15-, would also have been a valid choice (depending on your data and what type of output you expect). This way, we can make the function recognize your date via format = "%d-%b-%y".
Check out ?as.Date and ?strptime for more information. Ping me if you require further guidance. Happy to help.
It looks like your X axis is a character rather than a date so the axis is sorted alphabetically rather than chronologically. I would try making the x values dates.