基于ggplot2迭代绘图并根据df2的unit字段动态设置y轴标签
问题原因
你之前嵌套循环的写法存在逻辑错误:嵌套循环会遍历所有type和unit的组合,每个type会重复生成3张对应不同unit的图,完全不符合需求。从你的df2规则可以看到,同一个type对应的unit是唯一的,不需要额外嵌套循环,只要在原来的单层循环里,每次提取当前type对应的unit传给ylab()即可。
修改后可运行代码
library(ggplot2) library(data.table) # 原有预处理代码保持不变 df1$date <- as.Date(df1$date) df1.m <- melt(df1, id = "date") df1.m2 = merge(df1.m, df2, by.x = "variable", by.y = "columns") for(my_type in unique(df1.m2$type)) { # 提取当前type对应的唯一unit值 my_unit <- unique(df1.m2$unit[df1.m2$type == my_type]) g <- ggplot(data = df1.m2[df1.m2$type == my_type,], aes(x=date, y = value, colour=variable)) + geom_line(size = 1, alpha = 1) + ylab(my_unit) # 直接传入提取到的unit作为y轴标签 print(g) # ggsave(paste0(my_type,".png")) }
运行后price类的图y轴标签为$,pct_change类的图y轴标签为%,quantity类的图y轴标签为空,完全匹配需求。如果担心同一个type出现多个unit的异常情况,也可以换成取第一个值的写法my_unit <- df1.m2$unit[df1.m2$type == my_type][1],效果一致。
内容的提问来源于stack exchange,提问作者ah bon
相关产品推荐
相关产品推荐

