0

I have got the following data frame

species <- c("Acer pseudoplatanus", "Acer pseudoplatanus")
position <- c("o", "c")
pd <- c(-0.1, -0.2) 
sd_pd <-c(0.001, 0.023)
md<- c(-0.3, -0.45) 
sd_md <-c(0.024, 0.03)
df <- data.frame (species,position, pd, sd_pd, md, sd_md)

Now I would like to plot the values of pd and md for both positions (o, c) with the according error bar. On the x axis I would like to have the position, and the points for pd and md should be colored differently. Since the error bars overlap I would like to separate the points along the x axis, I tried it with ggplot and geom_point(position = position_dodge(0.5)) but that didn't work. Does someone know how to separate the points?

stefan
  • 90,330
  • 6
  • 25
  • 51

1 Answers1

1

The issue is that your data is spread over multiple columns, i.e. you have to reshape your dataset to make position_dodge work:

library(tidyr)
library(ggplot2)
library(dplyr, warn = FALSE)

df |>
  rename(mean_pd = pd, mean_md = md) |>
  pivot_longer(-c(species, position),
    names_to = c(".value", "variable"),
    names_sep = "_"
  ) |>
  ggplot(aes(position, mean, color = variable)) +
  geom_point(position = position_dodge(width = .9)) +
  geom_errorbar(aes(ymin = mean - sd, ymax = mean + sd),
    position = position_dodge(width = .9), width = .6
  )

enter image description here

stefan
  • 90,330
  • 6
  • 25
  • 51
  • Nice, thank you. Could you explain to me how the restructuring of the data frame works? I don't get that piece of code – user18487205 May 16 '23 at 20:37
  • 1
    (: Yeah. That's one of the advanced features of pivot_longer. In the standard case pivoting will give us one name column and one value column. Instead using the special `".value"` allows to have multiple value columns in one go. To this end I first rename to get consistent names. For your case the first part (mean or sd) becomes the name of the value column, and the second part become the categories of the name column (which I named variable). `names_sep` sets the separator used to split the column names into the two parts. – stefan May 16 '23 at 20:46