首页 > 解决方案 > ggplot - 我可以绘制每个方面的所有数据,同时分割另一个变量吗?

问题描述

我正在尝试创建一个按帐户类型和年份划分的帐户图表,但我希望所有数据都在每个方面,但如果不是我想要集中的部分,则只是在后台。

使用下面的虚拟数据,如果我只想按帐户类型随着时间的推移进行帐户,以显示我希望它显示的内容。

df1 <- data.frame(acc_type=rep(c("cash", "credit"), each=10),
                 year = as.factor(rep(2019, each = 20)),
                 x_date=seq(10),
                 accounts=runif(20, 1000, 10000))


df1$acc_type2 <- df1$acc_type

ggplot(df1, aes(x_date,accounts, group=acc_type)) + 
  geom_line(data=df1[,3:5], aes(x=x_date, y=accounts, group=acc_type2), colour="grey") +
  geom_line() + 
  facet_wrap(~ acc_type, nrow = 2)

在此处输入图像描述

然而,当我介绍年份时,数据有点搞笑

df2 <- data.frame(acc_type=rep(c("cash", "credit"), each=10),
                  year = as.factor(rep(2020, each = 20)),
                 x_date=seq(10),
                 accounts=runif(20, 1000, 10000))

df2$acc_type2 <- df2$acc_type

df3 <- rbind(df1, df2)
df3$year2 <- df3$year


ggplot(df3, aes(x_date,accounts, group=acc_type,colour= year)) + 
  geom_line(data=df3[,-(1:2)], aes(x=x_date, y=accounts, group=acc_type2, colour = year2), colour="grey") +
  geom_line() + 
  facet_wrap(~ acc_type, nrow = 2)

在此处输入图像描述

然后数据看起来没有被正确分组,任何关于如何正确分组并将对背景不那么重要的数据的帮助将不胜感激。

标签: rggplot2

解决方案


我相信这就是你所追求的。诀窍是不要在第二个数据中选择构面分组变量:

library(ggplot2)
library(dplyr)
ggplot(data=df3, aes(x=x_date, y=accounts)) + 
  geom_line(data = select(df3, -acc_type),
            aes(group = interaction(acc_type2,year)), color = "gray") +
  geom_line(aes(color= year)) + 
  facet_wrap(~acc_type, nrow = 2)

在此处输入图像描述


推荐阅读