r - 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)
解决方案
对于您的具体情况,问题是您没有引用Male/Female
and 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")
推荐阅读
- mysql - Student's report
- sql-server - Dropping clustered PK creating clustered index
- php - 在 Woocommerce 购物车和结帐中显示产品缩略图和属性
- kubernetes - 无法完全删除 Kubernetes CustomResource
- c# - 模型中的两个外键引用同一个表
- guava - 原始价值的番石榴缓存
- laravel-5 - 如果没有活动课程,则无法从存储中启动带有轮播的幻灯片图像
- vba - 日常任务自动化 - 将 1 个工作簿中的 2 个单元格复制并粘贴到另一个工作簿的最后一行
- hive - 带横向视图的 HIVE 查询,Json_Tuple
- python - scipy 约束非 x0 参数