Custom R visual times out in powerBI - r

I'm attempting to get a r visualization running in PowerBI. It runs fine in R, but for some reason it never finishes loading in PowerBI (no error message, just the timeout screen after 5 minutes). After some experimenting, I've noticed that if I remove one plotly overlay from the create and save widget section, it will load fine. It doesn't matter which one.
I am new to R and powerBi, so any advice on a workaround would be really appreciated.
source('./r_files/flatten_HTML.r')
############### Library Declarations ###############
libraryRequireInstall("ggplot2");
libraryRequireInstall("plotly");
####################################################
################### Actual code ####################
# plot histogram of risk density using monte carlo output
x = Values[,1]; #grab first column of dataframe as dataframe
# create CDF function and overlay onto histogram
cdf = ecdf(x);
# calculate mean cordinates to draw a mean line for selected data
meancordinates = function(xdata) {
v = sum(xdata)
meanxcord = v/length(xdata)
meancord = list(meanxcord = meanxcord, meanycord = cdf(meanxcord))
return(meancord)
};
mean = meancordinates(x);
# calculate median cordinates to draw a median line for selected data
mediancordinates = function(xdata) {
medianxcord = median(xdata)
mediancord = list(medianxcord = medianxcord, medianycord = cdf(medianxcord))
return(mediancord)
};
median = mediancordinates(x)
# calculate the 80% cordinates to draw a 80% line for selected data
eightycordinates = function(xdata) {
eightyxcord = x[which(abs(cdf(xdata)-0.80) == min(abs(cdf(xdata)-0.80)))]
eightycord = list(eightyxcord = eightyxcord, eightyycord = cdf(eightyxcord))
return(eightycord);
}
eighty = eightycordinates(x);
####################################################
############# Create and save widget ###############
p = plot_ly(x = x, type = "histogram", histnorm = "probability density", name = "Histogram")
p = p %>% add_segments(
x = median$medianxcord, xend = median$medianxcord,
y = 0, yend = median$medianycord,
name = "Median")
p = p %>% add_segments(
x = eighty$eightyxcord, xend = eighty$eightyxcord,
y = 0, yend = eighty$eightyycord,
name = "80%")
p = p %>% add_segments(
x = mean$meanxcord, xend = mean$meanxcord,
y = 0, yend = mean$meanycord,
name = "Mean")
p = p %>% add_lines(x = x, y = cdf(x), name = "CDF");
internalSaveWidget(p, 'out.html');
####################################################

Related

Error: x,y coords given but no window specified (spatstat)

I am generating a landscape pattern that evolves over time. The problem with the code is that I have clearly defined a window for the object bringing up the error but the window is not being recognised. I also do not see how any points are falling outside of the window, or how that would make a difference.
library(spatstat)
library(dplyr)
# Define the window
win <- owin(c(0, 100), c(0, 100))
# Define the point cluster
cluster1 <- rMatClust(kappa = 0.0005, scale = 0.1, mu = 20,
win = win, center = c(5,5))
# define the spread of the points
spread_rate <- 1
new_nests_per_year<-5
years<-10
# Plot the initial cluster
plot(win, main = "Initial cluster")
points(cluster1, pch = 20, col = "red")
newpoints<-list()
# Loop for n years
for (i in 1:years) {
# Generate new points that spread from the cluster
newpoints[[1]] <-rnorm(new_nests_per_year, mean = centroid.owin(cluster1)$y, sd = spread_rate)
newpoints[[2]] <-rnorm(new_nests_per_year, mean = centroid.owin(cluster1)$x, sd = spread_rate)
# Convert the list to a data frame
newpoints_df <- data.frame(newpoints)
# Rename the columns of the data frame
colnames(newpoints_df) <- c("x", "y")
# Combine the new points with the existing points
cluster1_df <- data.frame(cluster1)
newtotaldf<-bind_rows(cluster1_df,newpoints_df)
cluster1<-as.ppp(newtotaldf, x = newtotaldf$x, y = newtotaldf$y,
window = win)
# Plot the updated cluster
plot(win, main = paste("Cluster after year", i))
points(cluster1, pch = 20, col = "red")
}
However, when I run line:
cluster1<-as.ppp(newtotaldf, x = newtotaldf$x, y = newtotaldf$y,
window = win)
I recieve the error:
Error: x,y coords given but no window specified
Why would this be the case?
In your code, if you use the command W = win it should solve the issue. I also believe you can simplify the command without specifying x and y:
## ...[previous code]...
cluster1 <- as.ppp(newtotaldf, W = win)
plot(win)
points(cluster1, pch = 20, col = "red")

R Apexcharter: Formatting tooltip

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

z-score limits for boxplots/ adding single lines to different grouped boxplot

I have several measured values from different sources, I want to put an upper and lower limit for a given Median of a single test ID. I have different tests grouped together as you see in the picture I have several so to say, each test have about 5 sources and each source has 3 Measured values. therefore I have put boxplots for each source over its data and had all the tests with the boxplots of the different sources grouped in one source. my problem starts when I want to put a z score limit over the data just one z score per test is registerd but i would rather have a certain line limit over all the boxplots and not have just single points where they are all connected ( see the pic )
here is my code without the data
## Libraries call
library(readxl)
require(tidyverse)
require(rlang)
library(dplyr)
require(tidyr)
require(stringr)
require(plotly)
require(ggplot2)
require(matrixStats)
require(openxlsx)
############################
# source comparision Functions
############################
# Mean und Median bauen
df$Mean = rowMeans(as.matrix(df[,c(6,7,8)]),na.rm = TRUE)
df$Median = rowMedians(as.matrix(df[,c(6,7,8)]),na.rm = TRUE)
# summarize for TestID
df_sum <-df%>%
group_by(TestID)%>%
summarise(Mean=mean(Mean)
,Max=max(Mean)
,Min=min(Mean)
,Median=median(Median)
,Std=sd(Mean)
,Mad=mad(Mean)
,z_limit_std=2*Std
,z_limit_mad=2*Mad
)
# Merge von summary und DLG Daten
df_Median<- df[,c('TestID','Median')]
df_sum_Median <- df_Median%>% group_by(TestID)%>% summarise(Median=median(Median))
df = merge(x = df, y = df_sum, by = "TestID")
############################
#Box Plot
############################
Plot_Data_df <- data.frame(df$TestID
,df$`measured_value 1`
,df$`measured_value 2`
,df$`measured_value 3`
,df$Median.y
,df$z_limit_std)
# Daten in einem String umformen und die measured_valuee mit subset Daten mit NA
dfboxplot <- data.frame(TestID = rep(paste0(Plot_Data_df$df.TestID, '_Test'), 3)
,measured_value = c(Plot_Data_df$df..measured_value.1.,
Plot_Data_df$df..measured_value.2.,
Plot_Data_df$df..measured_value.3.)
,Median = rep(Plot_Data_df$df.Median.y, 3)
,z_limit = rep(Plot_Data_df$df.z_limit_std, 3)
)
dfboxplot$lower_limit <- dfboxplot$Median - dfboxplot$z_limit
dfboxplot$upper_limit <- dfboxplot$Median + dfboxplot$z_limit
plot <-plot_ly(dfboxplot, x = ~TestID, y = ~measured_value , color = ~Lab, type = "box",inherit=FALSE) %>%
layout(boxmode = "group",
xaxis = list(title='Test ID'),
yaxis = list(title= ' measured_value'))%>%
plotly::add_lines(data = dfboxplot # lower limit einführen
,y= ~Median
,x= ~TestID
,type = 'scatter'
,mode = 'lines'
,showlegend = FALSE
,line = list(color = 'rgb(0, 0, 0)',
width = 1)
,name = 'Median'
)%>% plotly::add_lines(data = dfboxplot # lower limit einführen
,y= ~upper_limit
,x= ~TestID
,type = 'scatter'
,mode = 'lines'
,showlegend = FALSE
,line = list(color = 'rgb(200, 0, 0)',
width = 1)
,name = 'upper limit'
)%>%
#
plot

Export Raster from R-INLA

so I am in dire need of help. I have finally managed to construct my R-INLA model and get it to graph as needed. via the code below:
First I create the stacks (note this is the very end of my INLA process, the mesh etc has already been done)
stk.abdu = inla.stack(data = list(y = 1, e = 0), A = list(abdu.mat, 1),tag = 'abdu', effects = list(list(i = 1:sc.mesh.5$n), data.frame(Intercept = 1,dwater=winter.abdu$dwater,elev=winter.abdu$elev,forest=winter.abdu$forest,developed=winter.abdu$developed,openwater=winter.abdu$OpenWater,barren=winter.abdu$barren,shrubland=winter.abdu$shrubland,herb=winter.abdu$herb,planted=winter.abdu$planted,wetland=winter.abdu$wetland,dist=winter.abdu$dwater)))
stk.quad = inla.stack(data = list(y = 0, e = 0.1), A = list(quad.mat, 1),tag = 'quad', effects = list(list(i = 1:sc.mesh.5$n), data.frame(Intercept = 1,dwater=dummy$dwater,elev=dummy$elev,forest=dummy$forest,developed=dummy$developed,openwater=dummy$openwater,barren=dummy$barren,shrubland=dummy$shrubland,herb=dummy$herb,planted=dummy$planted,wetland=dummy$wetland,dist=dummy$dwater)))
stk.prd<-inla.stack(data = list(y = NA), A = list(Aprd, 1),tag = 'prd', effects = list(list(i = 1:sc.mesh.5$n), data.frame(Intercept = 1,dwater=prddf2$dwater,elev=prddf2$elev,forest=prddf2$forest,developed=prddf2$developed,openwater=prddf2$openwater,barren=prddf2$barren,shrubland=prddf2$shrubland,herb=prddf2$herb,planted=prddf2$planted,wetland=prddf2$wetland,dist=prddf2$dwater)))
stk.all.prd = inla.stack(stk.abdu,stk.quad,stk.prd)
Next I fit my model
ft.inla.prd<-inla(y ~ 0 + Intercept + elev + dwater + forest+ developed + f(inla.group(dist,n=50,method="quantile"),model="rw1",scale.model=TRUE)+f(i,model=sc.spde),family="binomial",data=inla.stack.data(stk.all.prd),control.predictor = list(A = inla.stack.A(stk.all.prd),compute=TRUE),E=inla.stack.data(stk.all.prd)$e,control.compute=list(dic = TRUE),control.fixed=list(expand.factor.strategy="INLA"))
Then I change the predicted values from logit to probabilities
ft.inla.prd$newfield <- exp(ft.inla.prd$summary.random$i$mean)/(1 + exp(ft.inla.prd$summary.random$i$mean))
And finally I use inla.mesh.project and levelplot to create my image
xmean <- inla.mesh.project(projgrid,ft.inla.prd$newfield)
levelplot(xmean, col.regions=topo.colors(99), main='Probability of Presence',xlab='', ylab='', scales=list(draw=FALSE))
So my problem is that I now want to export this data (what is projected as the graph) as a raster so that I can work with it in ArcGIS. However, I have not been able to find a way to do so.
Any input is greatly appreciated

rcharts weird numbers in the y axis

The file to generate the graph can be downloaded from https://db.tt/hHYq0mSA. I'm sharing a link because dput generates a huge output. This is what I'm runing
require(rCharts)
dense<-readRDS("dense.RDS")
nPlot(x = "minutes", y = "FBS", data = dense, type = "lineChart")
This is what I get
What are the numbers (63382626 and 67270968) in the Y axis? how can I make them go away?
Thanks!
The strange digits are the final digits of the min and max of y
> options(digits=12)
> min(dense[,2])
[1] 0.000239026338263
> max(dense[,2])
[1] 0.0417486727097
You need to add some formatting rules on the y axis ticks:
require(rCharts)
dense<-readRDS("dense.RDS")
n1 <- nPlot(x = "minutes", y = "FBS", data = dense, type = "lineChart")
n1$yAxis(tickFormat = "#! function(d) {return d3.format(',.2f')(d)} !#")
n1
Aternative you can set the domain of the yaxis and keep the digits
require(rCharts)
dense<-readRDS("../Downloads/dense.RDS")
n1 <- nPlot(x = "minutes", y = "FBS", data = dense, type = "lineChart")
n1$chart(forceY = c(0, 0.05))
n1

Resources