r-在for循环中使用ggplot2的多个绘图



我看了这些问题(1)和(2),但它们似乎与我的问题无关。

我试图首先创建色带(在for循环外部),并在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 ...`

我正在使用最小、最大点来细化ribbon,然后想添加p_1D、p_2D点和线。我不知道你所说的ggplot2图形的有利方式是什么意思?我使用for循环来覆盖不同的绘图。如果没有for循环,我该怎么做?

您还没有提供可复制的示例,所以我将尝试解释我将尝试的内容:

将绘图保存到列表中,每个列表元素中的功能区都相同。然后循环浏览列表并添加不同的线和点。然后将图例名称添加到每个列表元素中。

然后可以从列表中访问绘图。

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

这就解决了问题。

最新更新