首页 > 解决方案 > ggplot2 的子集数据

问题描述

我将数据保存在多个数据集中,每个数据集中包含四个变量。dt想象一下由变量Country, Male/Female, Birthyear,组成的data.table 之类的东西Weighted Average Income。我想创建一个图表,您只能看到一个国家按出生年份划分的加权平均收入,并按男性/女性划分。我已经使用该facet_grid()函数来获取所有国家/地区的图表网格,如下所示。

ggplot() + 
 geom_line(data = dt,
           aes(x = Birthyear, 
               y = Weighted Average Income,
               colour = 'Weighted Average Income'))+
 facet_grid(Country ~ Male/Female)

但是,我尝试仅针对一个国家/地区隔离图表,但下面的代码似乎不起作用。如何正确子集数据?

ggplot() + 
 geom_line(data = dt[Country == 'Germany'],
           aes(x = Birthyear, 
               y = Weighted Average Income,
               colour = 'Weighted Average Income'))+
 facet_grid(Country ~ Male/Female)

标签: rggplot2subset

解决方案


对于您的具体情况,问题是您没有引用Male/Femaleand Weighted Average Income。此外,您的数据和基本美学应该可能是ggplot而不是geom_line。这样做会将这些隔离到单层,如果要添加例如geom_smooth.

所以要解决你的问题,你可以做

library(tidyverse)
plot <- ggplot(data = dt[Country == 'Germany'], 
       aes(x = Birthyear, 
           y = sym("Weighted Average Income"),
           col = sym("Weighted Average Income")
       ) + #Could use "`x`" instead of sym(x) 
  geom_line() + 
  facet_grid(Country ~ sym("Male/Female")) ##Could use "`x`" instead of sym(x)
plot

现在ggplot2实际上有一个(鲜为人知的)内置功能来更改您的数据,所以如果您想将此与包含所有国家/地区的图进行比较,您可以这样做:

plot %+% dt # `%+%` is used to change the data used by one or more layers. See help("+.gg")

推荐阅读