0

How to develop a boxplot using the inbuilt dataset "trees" in ggplot2.

I tried creating a boxplot keeping aes ( x and y) but it creates a boxplot againts "Girth" and "Volume", while I need a boxplot which the R base creates for the same data only using "

boxplot(trees)
stefan
  • 90,330
  • 6
  • 25
  • 51

1 Answers1

0

ggplot2 works different from base R plotting, i.e. to create a boxplot of several columns you first have to reshape your data to long format using e.g. tidyr::pivot_longer:

library(ggplot2)
library(tidyr)

trees_long <- trees |> 
  pivot_longer(everything(), names_to = "name", values_to = "value")

trees_long
#> # A tibble: 93 × 2
#>    name   value
#>    <chr>  <dbl>
#>  1 Girth    8.3
#>  2 Height  70  
#>  3 Volume  10.3
#>  4 Girth    8.6
#>  5 Height  65  
#>  6 Volume  10.3
#>  7 Girth    8.8
#>  8 Height  63  
#>  9 Volume  10.2
#> 10 Girth   10.5
#> # … with 83 more rows

ggplot(trees_long, aes(name, value)) + 
  geom_boxplot()

stefan
  • 90,330
  • 6
  • 25
  • 51