Home > database >  How to plot a boxplot with correctly spaced continuous x-axis values and a grouping variable in ggpl
How to plot a boxplot with correctly spaced continuous x-axis values and a grouping variable in ggpl

Time:01-27

I am trying to make a boxplot with a continuous x-axis where the x-axis labels are correctly spaced by their numeric value. I found the answer from enter image description here

But when I add fill=class, it doesn't appear to do anything and produces the exact same plot.

I would like the boxplot to show the class grouping in each year (shown below), but have the correct x-axis spacing from the first plot.

ggplot(data=df, aes(x=x, y=y, fill=class)) 
  geom_boxplot()

enter image description here

CodePudding user response:

In your data, you have a discrete variable, i.e., class. However, you need the data to be grouped by class and x_int. So, we can specify this grouping by using interaction in the group argument for x_int and class. Then, fill with class.

library(tidyverse)

df %>% 
  ggplot(aes(x=x_int, y=y, group = interaction(x_int, class), fill = class))  
  geom_boxplot()

Output

enter image description here

  •  Tags:  
  • Related