在循环使用GGPLOT2多条曲线(Multiple plots using ggplot2 in f

2019-09-20 16:03发布

我看着这些问题(1)和(2) ,但是,他们似乎没有要切合我的问题在这里。

我想首先创建带(外for循环),并添加了一堆线和点地块内的for循环。 但是,最后的情节只包含了最近的循环,而不是所有的人都行/分。 这整个代码是一个功能,我想从函数返回的ggplot(P,在这种情况下)对象,以便以后可以食用。

hist_points_cols_val<-hist_points_cols(hist_points)
hist_points_labels_val<-hist_points_labels(hist_points)
p <- ggplot()+
geom_ribbon(aes(x = x_labels , ymin = Min , ymax = Max),data=t_out_summary,colour = '#ece9d8',fill = '#ff9999',alpha = 0.4)+
geom_ribbon(aes(x = x_labels , ymin = Qtr1 , ymax = Qtr3),data=t_out_summary,colour = '#ece9d8',fill = '#33ff99',alpha = 0.2)+
scale_x_discrete(name=scale_x, labels=plot_labels)+
scale_y_continuous(name=scale_y, labels = percent_format())+
geom_line(aes(x = x_labels,y = Median,colour="Median"),data=t_out_summary)+
geom_point(aes(x = x_labels,y = Median,colour="Median"),data=t_out_summary,shape=4)

print(hist_points_cols_val)
print(hist_points_labels_val)
for( i in 1: length(hist_points)){
p   <- p + geom_line(aes(x = x_labels,y = t_out_summary[[hist_points_cols_val[i]]],colour=hist_points_labels_val[i]),data=t_out_summary,linetype='dashed')+
    geom_point(aes(x = x_labels,y = t_out_summary[[hist_points_cols_val[i]]],colour=hist_points_labels_val[i]),data=t_out_summary,shape=4)      
}

p<-p+scale_colour_hue(name="Legend")

数据是这样的:

`> str(t_out_summary)
'data.frame':   12 obs. of  11 variables:
 $ Min     : num  0.121 0.132 0.145 0.164 0.172 ...
 $ Qtr1    : num  0.154 0.165 0.174 0.191 0.2 ...
 $ Median  : num  0.184 0.195 0.203 0.218 0.225 ...
 $ Qtr3    : num  0.22 0.231 0.238 0.249 0.253 ...
 $ Max     : num  0.398 0.381 0.37 0.351 0.339 ...
 $ p_1D    : num  0.16 0.169 0.176 0.197 0.207 ...
 $ p_2D    : num  0.153 0.163 0.171 0.193 0.204 ...
 $ p_1W    : num  0.168 0.179 0.187 0.204 0.215 ...
 $ p_2W    : num  0.141 0.154 0.163 0.184 0.196 ...
 $ p_1M    : num  0.146 0.157 0.165 0.186 0.201 ...
 $ x_labels: int  1 2 3 4 5 6 7 8 9 10 ...`

我使用的最小,最大点克里特色带,然后想补充p_1D,p_2D点和线。 我不知道你是什么意思的有益方式GGPLOT2图形是什么意思? 我使用的for循环覆盖不同的地块。 我如何做没有for循环?

Answer 1:

您还没有提供的可再现的例子,所以我会尽量解释什么,我会尝试:

保存您的打印到列表中,用丝带在每一个列表元素相同。 然后遍历列表,并添加不同的线和点。 随后添加到每个列表元素的传奇名。

然后,你可以从列表中访问该地块。



Answer 2:

hist_summ<-melt(as.matrix(hist_summary))
geom_line(aes(x=Var2,y=value,colour = Var1,group=Var1),data=hist_summ)

这解决了问题。



文章来源: Multiple plots using ggplot2 in for loop
标签: r ggplot2