在这段代码中,我想要在循环中为每个alpha和y轴(min(Pro_df$Relative_Error),max(Pro_df$Relative_Error))绘制ggplot,在图中每个alpha都是单独的,这意味着我想要7 ggplot。另外,我希望在每个alpha的图形中分别显示geom_boxplot。我试着用下面的代码来做这件事,但是它不起作用。
library(ggplot2)
library(gganimate)
Pro_df <- data.frame(
x = integer(0),
Alpha = numeric(0),
Relative_Error = numeric(0))
mu=7 # Mean Value
sigma2=4 # Variance value
for (alpha in c(0.001,0.01,0.025,0.05,0.1,0.25,0.375))
{
for (i in 1:13)
{
E_PDF=dnorm(i,mean=mu,sd=sqrt(sigma2))
Relative_Error=(5-E_PDF)/(1-E_PDF)
newrow <- data.frame(x = i,
Alpha = alpha,
Relative_Error = Relative_Error)
Pro_df <- rbind(Pro_df, newrow)
}所有前面的代码都可以正常工作,现在我想绘制我的ggplot和boxplot,所以在结束第一个循环之前,我写了以下代码,但它没有像我在上面的问题中希望的那样工作。
print(map2 <- ggplot() +
geom_boxplot(data = Pro_df,
aes( , y =Relative_Error),
colour = "red", size = .5))
print(ggplot(Pro_df, aes(x =x, y =Relative_Error, colour = Alpha)) +
geom_line() +
ylim(min(Pro_df$Relative_Error),max(Pro_df$Relative_Error)))
}发布于 2020-10-10 04:09:17
我并不完全清楚你最终想要的输出是什么,但无论如何,你都缺少一种在创建时在循环中累积绘图的方法。在下面的代码片段中,我在循环开始之前实例化了一个列表,并在循环中添加了每个绘制列表。循环完成后,您现在可以浏览列表中的曲线图,例如,通过调用print(lst.plots$[["map2"]]$[["0.375"]])来查看最后的箱线图。
library(ggplot2)
library(gganimate)
Pro_df <- data.frame(
x = integer(0),
Alpha = numeric(0),
Relative_Error = numeric(0))
mu=7 # Mean Value
sigma2=4 # Variance value
lst.plots=list(map2 = list(),
other = list())
for (alpha in c(0.001,0.01,0.025,0.05,0.1,0.25,0.375))
{
for (i in 1:13)
{
E_PDF=dnorm(i,mean=mu,sd=sqrt(sigma2))
Relative_Error=(5-E_PDF)/(1-E_PDF)
newrow <- data.frame(x = i,
Alpha = alpha,
Relative_Error = Relative_Error)
Pro_df <- rbind(Pro_df, newrow)
}
print(map2 <- ggplot() +
geom_boxplot(data = Pro_df,
aes( , y =Relative_Error),
colour = "red", size = .5))
print(other <- ggplot(Pro_df, aes(x =x, y =Relative_Error, colour = Alpha)) +
geom_line() +
ylim(min(Pro_df$Relative_Error),max(Pro_df$Relative_Error)))
lst.plots$map2[[as.character(alpha)]]=map2
lst.plots$other[[as.character(alpha)]]=other
}https://stackoverflow.com/questions/64284909
复制相似问题