0

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 ?

1
  • Is box, check please Commented Oct 25, 2021 at 10:17

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.