Leprechault
Leprechault

Reputation: 1823

ggplot2: Problem with geom_boxplot representation for two numerical variables

I'd like to make an error representation in a boxplot (upper and lower quartiles, whiskers) without success. I have two exploratory variables (distance and radius) and if I make a mean plot with the error bars is OK, but if I try to make the same in a boxplot, I don't have the 5 radius for each distance. In my example:

# Open my ds
sim_F<-read.csv("https://raw.githubusercontent.com/Leprechault/trash/main/rad_dist_prob.csv")

# Aggregate mean
df_err<-sim_F%>%
  group_by(distance,radius) %>%
  summarize(error = mean(error, na.rm = TRUE)*100)
df_err

# Aggregate standart error
df_sd_err<-sim_F%>%
  group_by(distance, radius) %>%
  summarize(sd = sd(error, na.rm = TRUE)/sqrt(998)*100)
df_sd_err
#

# The errorbars overlapped, so use position_dodge to move them horizontally
pd <- position_dodge(0.1)

# First create a mean +-SD error bar
ggplot(data=df_err, aes(x=distance, y=error, color=as.factor(radius))) + 
    geom_errorbar(data=df_err,mapping=aes(ymin=error-df_sd_err$sd, ymax=error+df_sd_err$sd),position=pd, width=10) +
    scale_x_continuous(breaks=seq(20, 100, by = 5)) +
      xlab ("Distance (m)") +
      ylab ("Error (%)")

1

# Create same pattern but in a boxplot
ggplot(data=df_err, aes(x=distance, y=error, color=as.factor(radius))) + 
    geom_boxplot() +
      xlab ("Distance (m)") +
      ylab ("Error (%)")

2 #

   # I don't have de 5 radius in each distance

# I try to:
ggplot(data=df_err, aes(x=as.factor(distance), y=error, color=as.factor(radius))) + 
    geom_boxplot() +
      xlab ("Distance (m)") +
      ylab ("Error (%)")

3

# Doesn't work too!!

Please, any ideas for my boxplot representation of 5 radius for each distance like my first plot with error bars? I don't like subdivisions in the plot using facet_wrap.

Upvotes: 0

Views: 680

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76545

The problem seems to be that after aggregating the data with summarise there is only one datum per group/subgroup of distance/radius and a box-and-whiskers plot no longer makes sense.
The code below doesn't aggregate the data, it simply converts the grouping variables to factor and plots them in the x axis. The y axis percent scale labels use package scales, function label_percent.

library(dplyr)
library(ggplot2)

sim_F %>%
  mutate(distance = factor(distance),
         radius = factor(radius)) %>%
  ggplot(aes(x = distance, y = error, color = radius)) +
  geom_boxplot() +
  scale_y_continuous(labels = scales::label_percent()) +
  xlab ("Distance (m)") +
  ylab ("Error (%)")

enter image description here

Data

URL <- "https://raw.githubusercontent.com/Leprechault/trash/main/rad_dist_prob.csv"
download.file(url = URL, destfile = "rad_dist_prob.csv")
sim_F <- read.csv("rad_dist_prob.csv")

Upvotes: 1

Related Questions