首页 > 解决方案 > 在 ggplot aes 中使用 .$ 访问器

问题描述

我希望有人可以向我解释为什么在 ggplot aes() 中使用 .$ 访问器会破坏我的情节的细节。

# 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

现在我们绘制:

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

产生:

破碎的情节

但这有效:

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

生产:

工作区

为什么?

谢谢!

标签: rggplot2

解决方案


推荐阅读