1

I was hoping someone could explain to me the details of why using the .$ accessor within ggplot aes() is breaking my plot.

# setup dataframe to plot
library(tidyverse)
library(ggplot2)
library(reshape2)

df <- data.frame(
  'x' = seq(0, 99, 5),
  'a' = sample(seq(0, 10), size = 20, replace = TRUE),
  'b' = sample(seq(5, 15), size = 20, replace = TRUE),
  'c' = rep(c(1, 2, 3, 4))
)

melt_df <- df %>%
  melt(df, id.vars = c('x', 'c'), measure.vars = c('a', 'b'), variable.name = 'var')

> head(melt_df)
   x c var value
1  0 1   a    10
2  5 2   a    10
3 10 3   a     9
4 15 4   a    10
5 20 1   a     8
6 25 2   a     3

Now we plot:

# produce broken plot using .$
melt_df %>%
  ggplot(aes(
    x = .$x,
    y = .$value,
    color = .$var)) +
  geom_point() + 
  geom_line() + 
  facet_grid(. ~ c)

Which produces:

Broken plot

But then this works:

# produce working plot
melt_df %>%
  ggplot(aes(
    x = x,
    y = value,
    color = var)) +
  geom_point() + 
  geom_line() + 
  facet_grid(. ~ c)

Producing:

Working plot

Why?

Thanks!

khornlund
  • 21
  • 2
  • You should never use `$` within `aes`. ggplot2 can reorder/split data internally. If you pass to `aes` a vector outside `ggplot`'s `data` (e.g., `melt_df$x`) this is not aligned with vectors inside it (e.g., the `c` column in `facet_grid`). Your second approach is the correct one. – Roland Nov 15 '18 at 06:54

0 Answers0