Is it possible to change the order of columns in heatmaply? - r

I have created a dendrogram with heatmaply with a dendrogram object from the dendextend package. I was wondering if there is a way to change the order of the columns: vs, am, carb, wt, drat, gear, etc. For example, I want to sort them alphabetically. Is this possible?
library(heatmaply)
library(tidyverse)
library(RColorBrewer)
library(dendextend)
custom_colors <- c("#B6E2D3", "#887BB0", "#FFD53D", "#EF7C8E", "#A1F7A1", "#EFE7BC", "#C26DBC", "#14C2DD",
"#5CD85A", "#AB6B51", "#39918C", "#FFA384", "#57DDF3", "#D0B49F", "#EEB5EB", "#74BDCB")
dend_example <- mtcars %>% dist %>% hclust(method = "ward.D2") %>%
as.dendrogram %>% color_branches(k=5) %>% color_labels
heatmaply_mtcars<- heatmaply(mtcars, hclustfun = hclust, hclust_method = "ward.D2",
Rowv = dend_example,
main = "mtcars",
show_dendrogram = c(TRUE, FALSE),
showticklabels = c(TRUE, TRUE),
scale_fill_gradient_fun = ggplot2::scale_fill_gradient2(high = "#025492"),
file = "heatmaply_mtcars.html",
column_text_angle = 30,
colorbar_thickness = 50)

I included a column dendrogram within heatmaply with the colv argument. The column dendrogram was rotated with the rotate function from the package dendextend:
dend_example <- mtcars %>% dist %>% hclust(method = "ward.D2") %>%
as.dendrogram %>% color_branches(k=5) %>% color_labels
column_dend <- t(mtcars) %>% dist %>% hclust(method = "ward.D2") %>%
as.dendrogram
column_dend <- column_dend %>% rotate(c(vector_with_labels))
heatmaply_mtcars<- heatmaply(mtcars, hclustfun = hclust, hclust_method = "ward.D2",
Rowv = dend_example,
Colv = column_dend,
main = "mtcars",
show_dendrogram = c(TRUE, FALSE),
showticklabels = c(TRUE, TRUE),
scale_fill_gradient_fun = ggplot2::scale_fill_gradient2(high = "#025492"),
file = "heatmaply_mtcars.html",
column_text_angle = 30,
colorbar_thickness = 50)

Related

Putting confidence interval on time series graphs

I made time series graph with dygraph package:
library(forecast)
library(dygraphs)
hw <- HoltWinters(ldeaths)
p <- predict(hw, n.ahead = 36, prediction.interval = TRUE)
all <- cbind(ldeaths, p)
f <- forecast(unemp.mod)
dygraph(all, "Deaths from Lung Disease (UK)") %>%
dySeries("ldeaths", label = "Actual") %>%
dySeries(c("p.lwr", "p.fit", "p.upr"), label = "Predicted")
Now I try to add confidence intervals to predictions:
gen_array <- function(forecast_obj){
actuals <- forecast_obj$x
lower <- forecast_obj$lower[,2]
upper <- forecast_obj$upper[,2]
point_forecast <- forecast_obj$mean
cbind(actuals, lower, upper, point_forecast)
}
dygraph(all, main = "graph_title") %>%
dyRangeSelector() %>%
dyRangeSelector(height = 40,
dateWindow = c("2011-04-01", "2019-4-01")) %>%
dySeries(name = "actuals", label = "actual") %>%
dySeries(c("lower","point_forecast","upper"), label = "Predicted") %>%
dyLegend(show = "always", hideOnMouseOut = FALSE) %>%
dyHighlight(highlightCircleSize = 5,
highlightSeriesOpts = list(strokeWidth = 2)) %>%
dyOptions(axisLineColor = "navy", gridLineColor = "grey")
But I get errors:
Error in dySeries(., name = "actuals", label = "actual") :
One or more of the specified series were not found. Valid series names are: ldeaths, p.fit, p.upr, p.lwr
How I can fix it?

How do you pass multiple arguments to a function inside a function?

So I'm trying to make cross tables for multi-response questions with both frequency and counts using expss. I am able to get the result I need by running the following code:
library(expss)
set.seed(1998)
expss_output_viewer()
# Example data set
x <- c("A","B","C")
area <- rep(x,each = 10)
p <- sample(c(0,1),30,replace = T)
q <- sample(c(0,1),30,replace = T)
r <- sample(c(0,1),30,replace = T)
mrdata <- data.frame(area,p,q,r)
# Creating the Table
mrdata %>%
tab_significance_options(keep = "none", sig_labels = NULL, subtable_marks = "greater", mode = "append") %>%
tab_cols(total(), mdset(p,q,r)) %>%
tab_cells(area) %>%
tab_stat_cases(label = "cases") %>%
tab_stat_cpct_responses(label = "%",total_row_position = "none") %>%
tab_pivot(stat_position = "inside_columns") %>% set_caption("Table 1")
However, seeing as this is a lot of code for a single table, I wanted to wrap it into a function to be able to create the tables quickly and without much clutter. I've tried doing it like this:
mrtable <- function(input,rowvar,colvars,capt ="Table 1") {
input %>%
tab_significance_options(keep = "none", sig_labels = NULL, subtable_marks = "greater", mode = "append") %>%
tab_cols(total(), mdset(colvars)) %>%
tab_cells(rowvar) %>%
tab_stat_cases(label = "cases") %>%
tab_stat_cpct_responses(label = "%",total_row_position = "none") %>%
tab_pivot(stat_position = "inside_columns") %>% set_caption(capt)
}
mrtable(input = mrdata,colvars = c(p,q,r),rowvar = area)
Running the function above returns:
Error: 'cro': all variables should be of the same length or length 1.
I can't figure out why it fails. Any help would be appreciated.
EDIT:
got it to work :
mrtable <- function(input,rowvar,...,capt ="Table 1") {
input %>%
tab_significance_options(keep = "none", sig_labels = NULL, subtable_marks = "greater", mode = "append") %>%
tab_cols(total(), mdset(...)) %>%
tab_cells(rowvar) %>%
tab_stat_cases(label = "cases") %>%
tab_stat_cpct_responses(label = "%",total_row_position = "none") %>%
tab_pivot(stat_position = "inside_columns") %>% set_caption(capt)
}
mrtable(input = mrdata,rowvar = area,p,q,r,capt = "Tab")

labels order by month name chronically in r plotly [duplicate]

I'm using the plotly package in R to build an R Shiny dashboard. I want to order my pie chart in a custom order (non-alphabetic, non-descending/ascending order). For some reason I can't find how to achieve this.
Help would be highly appreciated!
# Get Manufacturer
mtcars$manuf <- sapply(strsplit(rownames(mtcars), " "), "[[", 1)
df <- mtcars %>%
group_by(manuf) %>%
summarize(count = n())
# Create custom order
customOrder <- c(df$manuf[12:22],df$manuf[1:11])
# Order data frame
df <- df %>% slice(match(customOrder, manuf))
# Create factor
df$manuf <- factor(df$manuf, levels = df[["manuf"]])
# Plot
df %>% plot_ly(labels = ~manuf, values = ~count) %>%
add_pie(hole = 0.6) %>%
layout(title = "Donut charts using Plotly", showlegend = F,
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
Ok, the answer is apparently twofold. Firstly, there is an argument in plot_ly, asking to sort the data on values (default is TRUE) or work with the custom order. Change this to FALSE.
Then, secondly, the order (clockwise) is different from the order in the data frame. The pie starts in the top right corner, and continues counterclockwise.
Hence, the following solves the problem:
# Get Manufacturer
mtcars$manuf <- sapply(strsplit(rownames(mtcars), " "), "[[", 1)
df <- mtcars %>%
group_by(manuf) %>%
summarize(count = n())
# Create custom order
customOrder <- c(df$manuf[12:22],df$manuf[1:11])
# Adjust customOrder to deal with pie
customOrder <- c(customOrder[1],rev(customOrder[2:length(customOrder)]))
# Order data frame
df <- df %>% slice(match(customOrder, manuf))
# Create factor
df$manuf <- factor(df$manuf, levels = df[["manuf"]])
# Plot
df %>% plot_ly(labels = ~manuf, values = ~count, sort = FALSE) %>%
add_pie(hole = 0.6) %>%
layout(title = "Donut charts using Plotly", showlegend = F,
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))

R Plotly: how to order pie chart?

I'm using the plotly package in R to build an R Shiny dashboard. I want to order my pie chart in a custom order (non-alphabetic, non-descending/ascending order). For some reason I can't find how to achieve this.
Help would be highly appreciated!
# Get Manufacturer
mtcars$manuf <- sapply(strsplit(rownames(mtcars), " "), "[[", 1)
df <- mtcars %>%
group_by(manuf) %>%
summarize(count = n())
# Create custom order
customOrder <- c(df$manuf[12:22],df$manuf[1:11])
# Order data frame
df <- df %>% slice(match(customOrder, manuf))
# Create factor
df$manuf <- factor(df$manuf, levels = df[["manuf"]])
# Plot
df %>% plot_ly(labels = ~manuf, values = ~count) %>%
add_pie(hole = 0.6) %>%
layout(title = "Donut charts using Plotly", showlegend = F,
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
Ok, the answer is apparently twofold. Firstly, there is an argument in plot_ly, asking to sort the data on values (default is TRUE) or work with the custom order. Change this to FALSE.
Then, secondly, the order (clockwise) is different from the order in the data frame. The pie starts in the top right corner, and continues counterclockwise.
Hence, the following solves the problem:
# Get Manufacturer
mtcars$manuf <- sapply(strsplit(rownames(mtcars), " "), "[[", 1)
df <- mtcars %>%
group_by(manuf) %>%
summarize(count = n())
# Create custom order
customOrder <- c(df$manuf[12:22],df$manuf[1:11])
# Adjust customOrder to deal with pie
customOrder <- c(customOrder[1],rev(customOrder[2:length(customOrder)]))
# Order data frame
df <- df %>% slice(match(customOrder, manuf))
# Create factor
df$manuf <- factor(df$manuf, levels = df[["manuf"]])
# Plot
df %>% plot_ly(labels = ~manuf, values = ~count, sort = FALSE) %>%
add_pie(hole = 0.6) %>%
layout(title = "Donut charts using Plotly", showlegend = F,
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))

Add mouseover to outliers but not other points?

I'd like to plot a large scatterplot using the highcharter package, but only allow mouse over on a few outliers. Is there a way to enable mouseTracking on one series but not the other?
df <- data.frame( x = rnorm(1000), y = rnorm(1000) )
df$sig <- ifelse( abs(df$x) > 2, "signif", "not")
library(highcharter)
hc <- highchart() %>%
hc_add_series_df(df, type = "scatter", group=sig)
Right now I can only disable mouse over on all points, but the hc_plotOptions says something about using a series array?
hc_plotOptions(hc, scatter = list( enableMouseTracking= FALSE ))
There are a lot of way to do what you want.
I think the simplest is use:
hchart(df, "scatter", hcaes(x, y, group = sig), enableMouseTracking = c(FALSE, TRUE))
(Note this is the development version of highcharter.)
Which is same as:
highchart() %>%
hc_add_series(data = df %>% filter(sig == "not"), type = "scatter", enableMouseTracking = FALSE) %>%
hc_add_series(data = df %>% filter(sig == "signif"), type = "scatter", enableMouseTracking = TRUE)
Or
highchart() %>%
hc_add_series(data = list_parse(df %>% filter(sig == "not")), type = "scatter", enableMouseTracking = FALSE) %>%
hc_add_series(data = list_parse(df %>% filter(sig == "signif")), type = "scatter", enableMouseTracking = TRUE)

Resources