如何在matplot中按条件分组数据并绘制带分类颜色的矩阵图?
解决方案
方法一:使用Base R的matplot
先根据Type列定义每组对应的颜色,再传给matplot的col参数即可实现按类别着色:
# 为不同Type分配颜色(Type=1用蓝色,Type=2用红色,可按需调整) line_colors <- ifelse(test$Type == 1, "blue", "red") # 绘制带分类颜色的矩阵图 matplot(t(test[,2:5]), type='l', col=line_colors, lty=1) # 可选:添加图例区分Type分组 legend("topleft", legend = unique(test$Type), col = unique(line_colors), lty=1, title="Type")
方法二:使用ggplot2(更灵活的可视化方案)
ggplot2需要先将宽格式数据转换为长格式,再按Type分组设置颜色:
library(ggplot2) library(tidyr) # 把宽格式数据转为长格式,同时生成Test的顺序标识 test_long <- test %>% pivot_longer(cols = starts_with("Test"), names_to = "Test", values_to = "Value") %>% mutate(Test_order = as.integer(sub("Test", "", Test))) # 绘制分组折线图 ggplot(test_long, aes(x = Test_order, y = Value, color = factor(Type), group = row.names(test_long))) + geom_line() + scale_x_continuous(breaks = 1:4, labels = paste0("Test", 1:4)) + labs(x = "Test", y = "Value", color = "Type") + theme_bw()
说明:group = row.names(test_long)是为了让原始数据的每一行对应一条独立折线,确保每条曲线的连贯性。
内容的提问来源于stack exchange,提问作者TJP2
相关产品推荐
相关产品推荐

