Manu_Gia
Manu_Gia

Reputation: 11

How do I group Xs in ggplot2?

I need to work on this plot so that the values on the x axis are grouped two-by-two plot I have now. enter image description here

To be clearer I attached a picture of what I would needplot I'd need:

enter image description here I simply edited it with GIMP to look a bit closer to what I'd like to get from the script, in the actual plot I produced on RStudio the x values are all evenly spaced.

The script I am currently using is:

ggplot(data.frame) + geom_point(data=data.frame,aes(x=xvar,y=yvar),colour="orange")+ geom_errorbar(aes(x=xvar, ymin=low, ymax=up), width=0.4, colour="orange")+ geom_point(data=data.frame,aes(x=xvar2,y=yvar2),colour="green")+ geom_errorbar( aes(x=xvar2, ymin=plow, ymax=pup), width=0.4, colour="green")

Upvotes: 1

Views: 60

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76402

Something like this?

  1. Aggregate the data with summarise;
  2. in the ggplot error bar and point layers, use position = position_dodge(width = 0.5).

In the example below I use the built-in data set mtcars.

library(ggplot2)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

mtcars %>%
  mutate(am = factor(am, labels = c("automatic", "manual"))) %>%
  summarise(
    mpg_min = min(mpg),
    mpg_max = max(mpg),
    mpg = mean(mpg),
    .by = c(cyl, am)
  ) %>% 
  ggplot(aes(cyl, mpg, color = am)) +
  geom_errorbar(aes(ymin = mpg_min, ymax = mpg_max),
                position = position_dodge(width = 0.5),
                width = 0.25) +
  geom_point(position = position_dodge(width = 0.5)) +
  scale_color_manual(values = c(automatic = "orange", manual = "green")) +
  theme_bw()

Created on 2024-10-07 with reprex v2.1.0

Upvotes: 0

Related Questions