silent_hunter
silent_hunter

Reputation: 2508

Plotting box-plots with for loop in Plotly

I made several plots with this lines of code:

dataset_numeric = dplyr::select_if(dataset, is.numeric)

par(mfrow=c(3,3))
for(i in 1:9) {
  boxplot(dataset_numeric[,i], main=names(dataset_numeric)[i])
}

And output from this plot is pic below :

enter image description here

So I want to do same but now with library(Plotly) so can anybody help me how to do that ?

Upvotes: 0

Views: 479

Answers (2)

tpetzoldt
tpetzoldt

Reputation: 5813

The following uses packages tidyr and ggplot2. First, the data are converted to a long table with pivot_longer, and then piped to ggplot. One issue to note in the example with one box only is that an explicit x aesthetic is needed, otherwise only the first box may be shown.

library("dplyr")
library("plotly")
library("ggplot2")
library("tidyr")

dataset <- as.data.frame(matrix(rnorm(99), ncol=9))

p <- pivot_longer(dataset, cols=everything()) %>%
  ggplot(aes(x=0, y = value)) +
  geom_boxplot() + facet_wrap( ~ name)

ggplotly(p)

Edit: a first had still an issue, that could be solved by adding x=0.

Upvotes: 1

Glastos
Glastos

Reputation: 57

I you want to use plotly and put all variables in the same graph, you can use add_trace() in a for loop to do what you want.

library(plotly)

dataset_numeric = dplyr::select_if(iris, is.numeric)

fig <- plot_ly(data = dataset_numeric, type = "box")

for (i in 1:ncol(dataset_numeric)) {
  fig <- fig %>% add_trace(y = dataset_numeric[,i])
}  

fig

If you want to have separate plot for each variable, you can use subplot()

all_plot <- list()
for (i in 1:ncol(dataset_numeric)) {
   fig <- plot_ly(data = dataset_numeric, type = "box") %>%
    add_trace(y = dataset_numeric[,i])
    all_plot <- append(all_plot, list(fig))
}  

plt <- subplot(all_plot)

plt

Upvotes: 1

Related Questions