首页 > 解决方案 > 趋势图无法正确绘制

问题描述

我有这个数据集:

Imputation  Distance    Clustering  2       3       4       5
Multiple    GOWER       PAM         1.6465  1.8604  1.9403  1.8752
Multiple    GOWER       DIANA       1.2760  1.9901  1.9834  1.9330
Multiple    GOWER       AGNES       2.0000  1.9739  1.9711  1.9613
Multiple    DEY         PAM         1.0161  0.7361  1.3657  1.2540
Multiple    DEY         DIANA       2.0000  2.0000  1.9279  1.9081
Multiple    DEY         AGNES       2.0000  2.0000  1.2890  1.2863
Single      GOWER       PAM         1.4669  1.6016  1.8037  1.9244
Single      GOWER       DIANA       1.3779  1.6891  1.6441  1.9429
Single      GOWER       AGNES       1.9630  1.9560  1.9907  1.9436
Single      DEY         PAM         1.0066  0.7093  0.7416  1.2659
Single      DEY         DIANA       1.0340  1.7889  1.7171  1.6917
Single      DEY         AGNES       2.0000  1.6093  1.6088  1.1616
None        GOWER       PAM         1.3351  1.7720  1.8558  1.9137
None        GOWER       DIANA       1.2963  1.9812  1.9420  1.9193
None        GOWER       AGNES       1.7059  1.9190  1.9411  1.9743

我想绘制一个图表,显示从 2 到 5 的值的趋势,以某种方式按分类变量分组。

我已经尝试融化数据集:

molten_cvnn <- melt(cvnn_data, id = c("Imputation", "Distance", "Clustering"))

然后尝试将单个分类变量作为一组进行绘图:

ggplot(molten_cvnn, aes(x = variable, y = value, group = Imputation)) + geom_line()

但这就是我得到的: 失败趋势

我想要这样的东西:

在此处输入图像描述

用不同的颜色、线型、形状等代表不同的类别组。

感谢您的预期帮助!

标签: rggplot2

解决方案


根据 OP 的帖子,我们可以重塑为“长”格式,并创建情节

library(dplyr)
library(tidyr)
library(ggplot2)
library(data.table)
cvnn_data %>% 
      pivot_longer(cols = `2`:`5`) %>% 
      mutate(rid = rowid(Imputation, name)) %>%
      ggplot(aes(rid, value, color = name)) + 
         geom_line()

或与ggpubr

library(ggpubr)
names(cvnn_data)[4:7] <- paste0("x", names(cvnn_data)[4:7])
lst1 <- ggline(cvnn_data,  "Imputation", c("x2", "x3", "x4", "x5"), color = "Distance")
lst1[[1]]
lst1[[2]]

或者这样做wrap_plots

library(patchwork)
wrap_plots(lst1)

推荐阅读