I create a rmarkdown html document and following is my code:
---
title: "PA"
output:
html_document:
css: custom.css
theme: journal
toc: true
toc_float:
collapsed: false
smooth_scroll: false
toc_depth: 4
---
<style>
.list-group-item.active, .list-group-item.active:focus, .list-group-item.active:hover {
background-color: blue;
}
</style>
<style type="text/css">
#TOC {
color: purple;
}
.toc-content {
padding-left: 30px;
padding-right: 40px;
}
h1 { /* Header 1 */
color: DarkBlue;
}
</style>
<div class="datatables html-widget html-widget-static-bound"
id="htmlwidget-3efe8ca4aa087193f03e"
style="width:960px;height:500px;">
```{r, echo=FALSE, message=FALSE, warning=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(lubridate)
library(ggplot2)
library(plotly)
library(DT)
library(knitr)
library(htmltools)
library(scales)
PA <- read.csv("PA.csv" , header = T , colClasses = c("Year"="factor", "Month"="factor"))
PA$Month <- as.numeric(as.character(PA$Month))
PA$Year <- as.numeric(as.character(PA$Year))
PA$date_label <- ymd( paste( PA$Year, month.abb[ PA$Month ], 01, sep = "-"))
```
```{r include = FALSE}
# If I want to use for-loop to print htmltools::tagList, this chunk is very important.
# However, I don't know why must need it.
DT::datatable(PA, extensions = 'Buttons', options = list(dom = 'Bfrtip',
buttons = list(c(I('colvis'), 'copy', 'print'), list(extend = 'collection',
buttons = c('csv', 'excel', 'pdf'),
text = 'Download'
)), searchHighlight = TRUE
))
ggplotly(ggplot(PA))
plot_ly(PA)
```
```{r, echo=FALSE, message=FALSE, warning=FALSE, results = 'asis'}
red.bold.italic.text <- element_text(face = "bold.italic", color = "red")
colors <- c('rgb(211,94,96)', 'rgb(128,133,133)', 'rgb(144,103,167)', 'rgb(171,104,87)', 'rgb(114,147,203)')
for(i in unique(PA$Products)) {
cat(" \n#", i, "{.tabset .tabset-pills} \n")
cat(paste("## Summary"), sep = "\n")
print(knitr::kable(mutate(summarise(group_by(PA[PA$Products == i,], Year, Company),sum(EPSUM), sum(Incurred)), LR.percent = `sum(Incurred)`/`sum(EPSUM)`/0.01), format = 'html'))
cat(paste("## Line Graph {.tabset .tabset-pills}"), sep = "\n")
cat(paste("### Line1"), sep = "\n")
print(htmltools::tagList(
ggplotly(ggplot(PA[PA$Products == i,], aes(x=date_label , y=EPSUM, col=Company , group=Company))
+ geom_line(size = 1)
+ scale_x_date(name = "Month", date_labels = "%b %Y", date_breaks = "2 month" )
+ labs(title = "EPSUM", x = "Time", y = "")
+ theme(title = red.bold.italic.text, axis.title = red.bold.italic.text)
+ scale_y_continuous(labels = comma)
)))
cat(paste("### Line2"), sep = "\n")
print(htmltools::tagList(
ggplotly(ggplot(PA[PA$Products == i,], aes(x=date_label , y=EPSUM, col=Company , group=Company))
+ geom_line(size = 1)
+ scale_x_date(name = "Month", date_labels = "%b %Y", date_breaks = "5 month" )
+ labs(title = "EPSUM", x = "Time", y = "")
+ theme(title = red.bold.italic.text, axis.title = red.bold.italic.text)
+ scale_y_continuous(labels = comma)
+ facet_wrap(~Company)
)))
cat(paste("## Bar Chart {.tabset .tabset-pills}"), sep = "\n")
cat(paste("### BAR1"), sep = "\n")
print(htmltools::tagList(
ggplotly(ggplot(summarise(group_by(PA[PA$Products == i,], Year, Company), sum(EPSUM)), aes(x=Year, y=`sum(EPSUM)`, fill=Company))
+ geom_bar(stat="identity", position=position_dodge())
+ labs(title = "EPSUM", x = "Time", y = "")
+ theme(title = red.bold.italic.text, axis.title = red.bold.italic.text)
+ scale_y_continuous(labels = comma)
)))
cat(paste("### BAR2"), sep = "\n")
print(htmltools::tagList(
ggplotly(ggplot(summarise(group_by(PA[PA$Products == i,], Year, Company), sum(EPSUM)), aes(x=as.factor(Year), y=`sum(EPSUM)`, fill=Year))
+ geom_bar(stat="identity", position=position_dodge())
+ labs(title = "EPSUM", x = "Time", y = "")
+ theme(title = red.bold.italic.text, axis.title = red.bold.italic.text)
+ scale_y_continuous(labels = comma)
+ facet_wrap(~Company)
)))
cat(paste("## Pie Chart"), sep = "\n")
print(htmltools::tagList(
plot_ly(summarise(group_by(PA[PA$Products == i,], Company, Year), sum(EPSUM)), labels = ~Company, values = ~`sum(EPSUM)`, type = 'pie',
textposition = 'inside',
textinfo = 'label+percent',
insidetextfont = list(color = '#FFFFFF'),
hoverinfo = 'text',
text = ~paste(Company, 'EPSUM', `sum(EPSUM)`),
marker = list(colors = colors,
line = list(color = '#FFFFFF', width = 1)),
showlegend = T) %>%
layout(title = '',
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
))
cat(paste("## Table"), sep = "\n")
print(htmltools::tagList(
DT::datatable(PA[PA$Products == i,][,c(-1,-12)], extensions = c('Buttons','Scroller'),
rownames = F, selection = list(target = 'row+column'),
options = list(pageLength = 400, dom = 'Bfrtip', scrollY = 200, scroller = TRUE,
buttons = list(c(I('colvis'), 'copy', 'print'),
list(extend = 'collection', buttons = c('csv', 'excel', 'pdf'),
text = 'Download')),
searchHighlight = TRUE)) %>%
formatCurrency(4:10, '', interval = 3, mark = ",")
))
cat(" \n")
}
```
data introduction:
5191 obs. of 11 variables (variables are not important, just know that there are 6 variables should remember: Products, Year, Month, Company, EPSUM, Incurred)
My question is: when I knit the html document, it takes too much time, is there any way to decrease the time?
After I knit, Internet Explorer cannot properly show, but Google Chrome can. I think it is because ActiveX. However, after I open it, it still cannot properly show. Any suggestion?
Not properly show.
It should show like this.
I think this post also figures out many other users' questions about how to use for-loop in R markdowm. And there are few reference on StackOverFlow.
Very appreciate.
Related
I am trying to produce a highcharter reactive plot in a shiny dashboard. The plot is based on product sales, which can be in different currencies. To that effect I have a dropdown list to select currencies, and based on the selected currency the plot changes. I managed to make the tooltip currency code dependent on the selection, but I cannot figure out how to apply the same reasoning to the axis values. Suppose I have the following data:
df = tibble(id = c(1:10),
item = c(sample(c('item1','item2','item3'), 10, replace = TRUE)),
sales = c(sample(c(500:1500), 10, replace = TRUE)),
units = c(sample(c(1:10), 10, replace = TRUE)),
currency = c(sample(c('GBP','EUR'), 10, replace = TRUE))
)
df = df %>%
group_by(item) %>%
summarise(total_sales = sum(sales),
total_units = sum(units),
currency = currency) %>%
ungroup()
# A tibble: 5 × 4
item currency total_sales total_units
<chr> <chr> <int> <int>
1 item1 EUR 1044 9
2 item1 GBP 5082 25
3 item2 EUR 1071 8
4 item2 GBP 1096 1
5 item3 EUR 2628 25
The user will select a currency, and the plot will be generated only for that currency. I would like to display the currency value in the tooltip and on the y-axis.
This is my code for the plot containing the tooltip:
df %>%
filter(currency == 'EUR') %>%
mutate(colors = colorize(total_units, scales::viridis_pal(option = "viridis",
begin = 0,
direction = 1)(length(unique(total_units))))) %>%
hchart('column', hcaes(x = item, y = total_sales,
color = colors)) %>%
hc_colorAxis(
min=min(df$total_units),
max=max(df$total_units ),
stops= color_stops(colors = cols),
marker = NULL
) %>%
hc_tooltip(
useHTML = TRUE,
formatter = JS(
"
function(){
outHTML = '<b> Product: </b>' + this.point.item + '<b><br> Sales:</b> '+ this.point.currency + ' ' + this.point.total_sales +
'<b><br> Number of Units Sold: </b>' + this.point.total_units
return(outHTML)
}
"
),
shape = "square", # Options are square, circle and callout
borderWidth = 0 # No border on the tooltip shape
) %>%
hc_yAxis(title = list(text = "Sales Amount",
align = "middle",
margin = 10,
style = list(
fontWeight = "bold",
fontSize = "1.4em"
)
),
labels = list(formatter = JS(
"function(){
data = this.value
return(data)
}"
))
)
If you then change the filter from 'EUR' to 'GBP' you can see that the tooltip updates automatically:
I would like the same dynamic prefix to appear on the y-axis to get this result automatically when 'GBP' is select, and vice-versa for 'EUR':
Any suggestions?
Inside chart.events.load it's possible to use update method to change suffix.
events: {
load: function() {
var chart = this,
yAxis = chart.yAxis[0],
lastTick = yAxis.tickPositions[yAxis.tickPositions.length - 1],
suffix = yAxis.ticks[lastTick].label.textStr.substr(-1, 1);
yAxis.update({
title: {
text: 'Revenue [' + suffix + ' €]'
}
})
}
}
Demo: https://jsfiddle.net/BlackLabel/b0yucdot/1/
API: https://api.highcharts.com/class-reference/Highcharts.Axis#update
I'm working in Rbookdown and I want to place a plot and a table in one figure, how can I achieve that? Below is the code i used so far. Can you help?
```{r echo=FALSE, message=FALSE, warning=FALSE, fig.height = 3.5, out.width = '70%', fig.align = "center"}
library(knitr)
library(kableExtra)
library(tidyverse)
library(latex2exp)
options(scipen=999)
mu = 0
sigma = 1
x = 1
# draw normal distribution
range = seq(mu - 4*sigma, mu + 4*sigma, 0.01)
y = dnorm(range, mu, sigma)
plot(range, y,
main = "Standard Normal Distribution", xlab = "Z-score", ylab = " ",
type = 'l', ylim = c(0, max(y) + 0.01), axes = FALSE)
axis(1, at = seq(mu - 4*sigma, mu + 4*sigma, sigma))
# Add area to the left of x
cord.a = c(0, seq(min(range), x, 0.01))
cord.b = c(dnorm(seq(min(range), x, 0.01), mu, sigma), 0)
polygon(cord.a, cord.b, col = "#61a5ff")
text(x = 1.1, y = -.06, TeX('$z = 1.00$'), cex = .8, xpd=NA)
text(x = 0, y = .15, TeX('$p = .8413$'), cex = .8, xpd=NA)
# Create standard normal table
options(digits = 4)
u=seq(0,3.09,by=0.01)
p=pnorm(u)
m=matrix(p,ncol=10,byrow=TRUE)
df.m = as.data.frame(m)
z.values = c("**0.0**", "**0.1**", "**0.2**", "**0.3**", "**0.4**", "**0.5**", "**0.6**",
"**0.7**", "**0.8**", "**0.9**", "**1.0**", "**1.1**", "**1.2**", "**1.3**",
"**1.4**", "**1.5**", "**1.6**", "**1.7**", "**1.8**", "**1.9**","**2.0**",
"**2.1**", "**2.2**", "**2.3**", "**2.4**", "**2.5**", "**2.6**", "**2.7**",
"**2.8**", "**2.9**", "**3.0**")
df.z.values = as.data.frame(z.values)
new.m = df.z.values %>%
bind_cols(df.m)
kable(new.m,
booktabs = TRUE,
col.names = c("$Z$", "0.00","0.01", "0.02", "0.03", "0.04",
"0.05", "0.06", "0.07", "0.08", "0.09"),
escape = FALSE,
caption = "Standaard Normaalverdeling",
linesep = "",
align = c('r')) %>%
kable_styling(font_size = 10)
Try this solution:
```{r echo=FALSE, message=FALSE, warning=FALSE, include = FALSE}
library(kableExtra)
#make and save our table into working directory
table1 <- head(mtcars[1:5]) %>%
kbl() %>%
kable_styling(full_width = F) %>%
save_kable("tab_kbl.png")
#make and save our plot into working directory
png('norm_pl.png')
plot(rnorm(10))
dev.off()
```
```{r,echo=FALSE, message=FALSE, warning=FALSE, fig.cap="My image", fig.align = "center"}
library(cowplot)
#combine our images in the one
img1 <- ggdraw() + draw_image("norm_pl.png", scale = 1)
img2 <- ggdraw() + draw_image("tab_kbl.png", scale = 1)
plot_grid(img1, img2)
```
An another variant
```{r, fig.align='center', fig.cap="My beautiful image"}
library(gridExtra)
library(grid)
library(cowplot)
t1 <- tableGrob(head(mtcars[1:5]), theme = ttheme_minimal())
p2 <- ggplot(mtcars, aes(cyl, mpg)) +
geom_point()
plot_grid(t1, p2, ncol = 2, rel_widths = c(2,1))
```
I don't get similar results when I use the same data and models using mlr and mlr3. Also I find mlr runs at least 20-fold faster. I used lung data from survival and I was able to replicate the difference in computation speed and results since I can't share my data.
mlr was completed in 1 min with C-index generally low compared to mlr3 that took 21 min to complete with C-index being much higher despite using same data, same preprocessing, same model and setting seed.
library(tidyverse)
library(tidymodels)
library(PKPDmisc)
library(mlr)
library(parallelMap)
library(survival)
# Data and Data Splitting
data = as_tibble(lung) %>%
mutate(status = if_else(status==1, 0, 1),
sex = factor(sex, levels = c(1:2), labels = c("male", "female")),
ph.ecog = factor(ph.ecog))
na <- sample(1:228, 228*0.1)
data$sex[na] <- NA
data$ph.ecog[na]<- NA
set.seed(123)
split <- data %>% initial_split(prop = 0.8, strata = status)
train <- split %>% training()
test <- split %>% testing()
# Task
task = makeSurvTask(id = "Survival", data = train, target = c("time", "status"))
# Resample
# For model assessment before external validation on test data
set.seed(123)
outer_cv = makeResampleDesc("CV", iter=4, stratify.cols = c("status")) %>%
makeResampleInstance(task)
# For feature selection and parameter tuning
set.seed(123)
inner_cv = makeResampleDesc("CV", iter=4, stratify.cols = c("status"))
# Learners
cox1 = makeLearner(id = "COX1", "surv.coxph") %>%
makeImputeWrapper(classes = list(factor = imputeMode(), numeric = imputeMedian()),
# Create dummy variable for factor features
dummy.classes = "factor") %>%
makePreprocWrapperCaret(ppc.center = TRUE, ppc.scale = TRUE) %>%
makeFeatSelWrapper(resampling = inner_cv, show.info = TRUE,
control = makeFeatSelControlSequential(method = "sfs"))
cox_lasso = makeLearner(id = "COX LASSO", "surv.glmnet") %>%
makeImputeWrapper(classes = list(factor = imputeMode(), numeric = imputeMedian()),
# Create dummy variable for factor features
dummy.classes = "factor") %>%
# Normalize numeric features
makePreprocWrapperCaret(ppc.center = TRUE, ppc.scale = TRUE) %>%
makeTuneWrapper(resampling = inner_cv, show.info = TRUE,
par.set = makeParamSet(makeNumericParam("lambda",lower = -3, upper = 0,
trafo = function(x) 10^x)),
control = makeTuneControlGrid(resolution = 10L))
cox_net = makeLearner(id = "COX NET", "surv.glmnet") %>%
makeImputeWrapper(classes = list(factor = imputeMode(), numeric = imputeMedian()),
# Create dummy variable for factor features
dummy.classes = "factor") %>%
# Normalize numeric features
makePreprocWrapperCaret(ppc.center = TRUE, ppc.scale = TRUE) %>%
makeTuneWrapper(resampling = inner_cv, show.info = TRUE,
par.set = makeParamSet(makeNumericParam("alpha", lower = 0, upper = 1,
trafo = function(x) round(x,2)),
makeNumericParam("lambda",lower = -3, upper = 1,
trafo = function(x) 10^x)),
control = makeTuneControlGrid(resolution = 10L))
# Benchmark
# parallelStartSocket(4)
start_time <- Sys.time()
set.seed(123)
mlr_bmr = benchmark(learners = list(cox1, cox_lasso, cox_net),
tasks = task,
resamplings = outer_cv,
keep.extract= TRUE,
models = TRUE)
end_time <- Sys.time()
mlr_time = end_time - start_time
# parallelStop()
mlr_res <- getBMRPerformances(mlr_bmr, as.df = TRUE) %>%
select(Learner = learner.id, Task = task.id, Cindex = cindex) %>%
mutate(Color_Package = "mlr",
Learner = word(str_replace(Learner, "\\.", " "), 1, -2))
##################################################################
library(mlr3verse)
# Task
task2 = TaskSurv$new(id = "Survival2", backend = train, time = "time", event = "status")
task2$col_roles$stratum = c("status")
# Resmaple
set.seed(123)
outer_cv2 = rsmp("cv", folds = 4)$instantiate(task2)
# For feature selection and parameter tuning
set.seed(123)
inner_cv2 = rsmp("cv", folds = 4)
# Learners
preproc = po("imputemedian", affect_columns = selector_type("numeric")) %>>%
po("imputemode", affect_columns = selector_type("factor")) %>>%
po("scale") %>>%
po("encode")
cox2 = AutoFSelector$new(learner = as_learner(preproc %>>%
lrn("surv.coxph")),
resampling = inner_cv2,
measure = msr("surv.cindex"),
terminator = trm("none"), # need to increase later
fselector = fs("sequential", strategy = "sfs")) # sfs is the default
cox2$id = "COX1"
cox_lasso2 = AutoTuner$new(learner = as_learner(preproc %>>%
lrn("surv.glmnet",
lambda = to_tune(p_dbl(lower = -3, upper = 0,
trafo = function(x) 10^x)))),
resampling = inner_cv2,
measure = msr("surv.cindex"),
terminator = trm("none"),
tuner = tnr("grid_search", resolution = 10))
cox_lasso2$id = "COX LASSO"
cox_net2 = AutoTuner$new(learner = as_learner(preproc %>>%
lrn("surv.glmnet",
alpha = to_tune(p_dbl(lower = 0, upper = 1)),
lambda = to_tune(p_dbl(lower = -3, upper = 1,
trafo = function(x) 10^x)))),
resampling = inner_cv2,
measure = msr("surv.cindex"),
terminator = trm("none"),
tuner = tnr("grid_search", resolution = 10))
cox_net2$id = "COX NET"
# Benchmark
desgin = benchmark_grid(tasks = task2,
learners = c(cox2, cox_lasso2, cox_net2),
resamplings = outer_cv2)
# future::plan("multisession")
# Error: Output type of PipeOp select during training (Task) incompatible with input type of PipeOp surv.coxph (TaskSurv)
start_time <- Sys.time()
set.seed(123)
mlr3_bmr = mlr3::benchmark(desgin)
end_time <- Sys.time()
mlr3_time = end_time - start_time
mlr3_res <- as.data.table(mlr3_bmr$score()) %>%
select(Task=task_id, Learner=learner_id, Cindex=surv.harrell_c) %>%
mutate(Color_Package = "mlr3")
mlr_res %>%
bind_rows(mlr3_res) %>%
ggplot(aes(Learner, Cindex, fill= Color_Package )) +
geom_boxplot(position=position_dodge(.8)) +
stat_summary(fun= mean, geom = "point", aes(group = Color_Package ),
position=position_dodge(.8), size = 3) +
labs(x="", y = " C-Index") +
theme_bw() + base_theme() + theme(legend.position = "top")
I found this code online at http://www.sthda.com/english/wiki/ggplot2-quick-correlation-matrix-heatmap-r-software-and-data-visualization
It provides instructions for how to create a correlation matrix heat map and it works well. However, I was wondering how to get little stars * next to the values in the matrix that are significant. How would I go about doing that. Any help is greatly appreciated!!
mydata <- mtcars[, c(1,3,4,5,6,7)]
head(mydata)
cormat <- round(cor(mydata),2)
head(cormat)
library(reshape2)
melted_cormat <- melt(cormat)
head(melted_cormat)
library(ggplot2)
ggplot(data = melted_cormat, aes(x=Var1, y=Var2, fill=value)) +
geom_tile()
# Get lower triangle of the correlation matrix
get_lower_tri<-function(cormat){
cormat[upper.tri(cormat)] <- NA
return(cormat)
}
# Get upper triangle of the correlation matrix
get_upper_tri <- function(cormat){
cormat[lower.tri(cormat)]<- NA
return(cormat)
}
upper_tri <- get_upper_tri(cormat)
# Melt the correlation matrix
library(reshape2)
melted_cormat <- melt(upper_tri, na.rm = TRUE)
# Heatmap
library(ggplot2)
ggplot(data = melted_cormat, aes(Var2, Var1, fill = value))+
geom_tile(color = "white")+
scale_fill_gradient2(low = "blue", high = "red", mid = "white",
midpoint = 0, limit = c(-1,1), space = "Lab",
name="Pearson\nCorrelation") +
theme_minimal()+
theme(axis.text.x = element_text(angle = 45, vjust = 1,
size = 12, hjust = 1))+
coord_fixed()
reorder_cormat <- function(cormat){
# Use correlation between variables as distance
dd <- as.dist((1-cormat)/2)
hc <- hclust(dd)
cormat <-cormat[hc$order, hc$order]
}
# Reorder the correlation matrix
cormat <- reorder_cormat(cormat)
upper_tri <- get_upper_tri(cormat)
# Melt the correlation matrix
melted_cormat <- melt(upper_tri, na.rm = TRUE)
# Create a ggheatmap
ggheatmap <- ggplot(melted_cormat, aes(Var2, Var1, fill = value))+
geom_tile(color = "white")+
scale_fill_gradient2(low = "blue", high = "red", mid = "white",
midpoint = 0, limit = c(-1,1), space = "Lab",
name="Pearson\nCorrelation") +
theme_minimal()+ # minimal theme
theme(axis.text.x = element_text(angle = 45, vjust = 1,
size = 12, hjust = 1))+
coord_fixed()
# Print the heatmap
print(ggheatmap)
ggheatmap +
geom_text(aes(Var2, Var1, label = value), color = "black", size = 4) +
theme(
axis.title.x = element_blank(),
axis.title.y = element_blank(),
panel.grid.major = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
axis.ticks = element_blank(),
legend.justification = c(1, 0),
legend.position = c(0.6, 0.7),
legend.direction = "horizontal")+
guides(fill = guide_colorbar(barwidth = 7, barheight = 1,
title.position = "top", title.hjust = 0.5))
cor() doesn't show the significance level, you may have to use rcorr() from Hmisc package
This is quite similar to what you want (the graphic output is not so nice though)
library(ggplot2)
library(reshape2)
library(Hmisc)
library(stats)
abbreviateSTR <- function(value, prefix){ # format string more concisely
lst = c()
for (item in value) {
if (is.nan(item) || is.na(item)) { # if item is NaN return empty string
lst <- c(lst, '')
next
}
item <- round(item, 2) # round to two digits
if (item == 0) { # if rounding results in 0 clarify
item = '<.01'
}
item <- as.character(item)
item <- sub("(^[0])+", "", item) # remove leading 0: 0.05 -> .05
item <- sub("(^-[0])+", "-", item) # remove leading -0: -0.05 -> -.05
lst <- c(lst, paste(prefix, item, sep = ""))
}
return(lst)
}
d <- mtcars
cormatrix = rcorr(as.matrix(d), type='spearman')
cordata = melt(cormatrix$r)
cordata$labelr = abbreviateSTR(melt(cormatrix$r)$value, 'r')
cordata$labelP = abbreviateSTR(melt(cormatrix$P)$value, 'P')
cordata$label = paste(cordata$labelr, "\n",
cordata$labelP, sep = "")
cordata$strike = ""
cordata$strike[cormatrix$P > 0.05] = "X"
txtsize <- par('din')[2] / 2
ggplot(cordata, aes(x=Var1, y=Var2, fill=value)) + geom_tile() +
theme(axis.text.x = element_text(angle=90, hjust=TRUE)) +
xlab("") + ylab("") +
geom_text(label=cordata$label, size=txtsize) +
geom_text(label=cordata$strike, size=txtsize * 4, color="red", alpha=0.4)
Source
difference_p is the P_value of correlation matrix,
ax5 draws the sns.heatmap and return as ax5
data=correlation_p
for y in range(data.shape[0]):
for x in range(data.shape[1]):
if data[y,x]<0.1:
ax4.text(x + 0.5, y + 0.5, '-',size=48,
horizontalalignment='center',
verticalalignment='center',
)
I'm developping a Shiny app to filter a database (like Excel), and I'd like to stop all the calculation of the app when a Drop Down Button is open. Do you know how could I do that please ? It's my first Shiny app, so I'm pretty sure that I made some silly mistakes.
In my Drop Down Button, I have a CheckBoxGroupInput, with the different choices for one variable of my database. Problem : I have to wait a few seconds between each selection inside the CheckBoxGroupInput, because the app is refreshing for each additionnal choice in the CheckBox.
An example for one variable :
ui :
dropdownButton(
label = "Country :", status = "default", width = 200, circle = FALSE,
actionButton(inputId = "country_all", label = "(Un)select all"),
uiOutput("countrybis")
),
verbatimTextOutput(outputId = "country_print")
server :
Function for refreshing each list in the different CheckBox :
Function_List_Data <- function(p_type, p_processchoice, p_year, p_variable, p_product, p_country,
p_item, p_season, p_region, p_calcamp){
if(p_processchoice == "GROSSVAR"){
data <- dataset_var[YEARBIS >= p_year[1] & YEARBIS <= p_year[2],]}
else if(p_processchoice == "YIELD"){
data <- dataset_rdt[YEARBIS >= p_year[1] & YEARBIS <= p_year[2],]}
else{data <- dataset[YEARBIS >= p_year[1] & YEARBIS <= p_year[2],]}
if (p_region == 2) {data <- data[REGION %in% list("EU-15","EU-27","EU-28")]}
else if (p_region == 3) {data <- data[REGION %in% list("C.I.S.")]}
if (p_calcamp == 2) {data <- data[`CAMPAIGN/CALENDAR` == "CAMPAIGN",]}
else if (p_calcamp == 3) {data <- data[`CAMPAIGN/CALENDAR` == "CALENDAR",]}
else if (p_calcamp == 4) {data <- data[`CAMPAIGN/CALENDAR` == "OTHERS",]}
if (!is.null(p_variable)) {data <- data[VARIABLE %in% p_variable]}
if (!is.null(p_product)) {data <- data[PRODUCT %in% p_product,]}
if (!is.null(p_country)) {data <- data[COUNTRY %in% p_country,]}
if (!is.null(p_item)) {data <- data[ITEM %in% p_item,]}
if (!is.null(p_season)) {data <- data[SEASON %in% p_season,]}
if(nrow(data)<1){ data <- data[1,] }
if (p_type == "VARIABLE"){List <- unique(unlist(data$VARIABLE), use.names = FALSE)}
else if (p_type == "PRODUCT"){List <- unique(unlist(data$PRODUCT), use.names = FALSE)}
else if (p_type == "COUNTRY"){List <- unique(unlist(data$COUNTRY), use.names = FALSE)}
else if (p_type == "ITEM"){List <- unique(unlist(data$ITEM), use.names = FALSE)}
else if (p_type == "SEASON"){List <- unique(unlist(data$SEASON), use.names = FALSE)}
return(List)
}
Calculation for the Country column :
Country_List <- reactive({
Function_List_Data(p_type = "COUNTRY",
p_processchoice = input$dataprocess_choice,
p_year = input$year,
p_variable = input$variable_list,
p_product = input$product_list,
p_country = NULL,
p_item = input$item_list,
p_season = input$season_list,
p_region = input$region,
p_calcamp = input$campaign_calendar)})
observeEvent(input$country_all, {
if (is.null(input$country_list)) {
updateCheckboxGroupInput(session = session, inputId = "country_list", selected = Country_List())}
else {updateCheckboxGroupInput(session = session, inputId = "country_list", selected = "")}
})
output$country_print <- renderPrint({
if(is.null(input$country_list)){"- ALL -"}
else{as.matrix(input$country_list)}
})
output$countrybis <- renderUI({
checkboxGroupInput(inputId = "country_list", label = "Choose", choices = sort(Country_List()), selected = input$country_list)
})
EDIT :
When I calculate the Country_List only when I click on the DropdownButton, it's not working, you can see the error on the screen :
Error received : the Country_List is calculate after the CheckBox is print
.
Button Select All / Unselect All :
observeEvent(input$country_all, {
Country_List <- Function_List_Data(p_type = "COUNTRY",
p_processchoice = input$dataprocess_choice,
p_year = input$year,
p_variable = input$variable_list,
p_product = input$product_list,
p_country = NULL,
p_item = input$item_list,
p_season = input$season_list,
p_region = input$region,
p_calcamp = input$campaign_calendar)
if (is.null(input$country_list)) {
updateCheckboxGroupInput(session = session, inputId = "country_list", selected = Country_List)}
else {updateCheckboxGroupInput(session = session, inputId = "country_list", selected = "")}})
RenderPrint :
output$country_print <- renderPrint({
if(is.null(input$country_list)){"- ALL -"}
else{as.matrix(input$country_list)}})
CheckBox :
output$countrybis <- renderUI({
observeEvent(input$Country_DropDown,{
print("bla")
Country_List <- Function_List_Data(p_type = "COUNTRY",
p_processchoice = input$dataprocess_choice,
p_year = input$year,
p_variable = input$variable_list,
p_product = input$product_list,
p_country = NULL,
p_item = input$item_list,
p_season = input$season_list,
p_region = input$region,
p_calcamp = input$campaign_calendar)
})
checkboxGroupInput(inputId = "country_list", label = "Choose", choices = sort(Country_List), selected = input$country_list) })