R 脚本:使用 ggplot2 向绘图的 ymax 添加填充

R script : add a padding to the ymax of the plot with ggplot2

我正在尝试为我正在绘制的最多 5 条曲线添加 20 的填充。

library(ggplot2)

... some code to compute 5 (bins) distributions y3(nSample,bin)

color_curve <- c("red", "green", "grey", "black")

max_y <- as.double(which.max(density(y3))+20)

# Save PDF - Chisquare
pdf(file="Chisquare_Distribution.pdf")
for (i in 1:nRed) {
  if (i == 1)
    plot(density(y3[,i]), col="blue", xlim=c(min(y3),max(y3)), ylim=c(0,max_y), main="z= 0.9595, 1.087, 1.2395, 1.45, 1.688")
  else
    lines(density(y3[,i]), col=color_curve[i-1])
}
dev.off()

但是我在执行时遇到以下错误:

Error in which.max(density(y3)) :
  'list' object cannot be coerced to type 'double'
Execution halted

我想将这个 20 的填充添加到所有 5 个分布的最大值,但它失败并出现此错误。

如何解决这个问题?

更新 1

感谢您提供建议的答案。不幸的是,现在,我得到了下图:

如您所见,y_limit 中的最大值对于 5 个分布来说太高了,我不知道它可能来自哪里。

更新 2

有了新命令,我得到了下图:

我在 5 个分布中搜索最大值时得到一个低估值。

编辑

我提供了生成图的完整代码 the input file:

my_data <- read.delim("Array_total_WITH_Shot_Noise.txt", header = FALSE, sep = " ")
array_2D <- array(my_data)
z_ph <- c(0.9595, 1.087, 1.2395, 1.45, 1.688)
b_sp <- c(1.42904922, 1.52601862, 1.63866958, 1.78259615, 1.91956918)
b_ph <- c(sqrt(1+z_ph))
ratio_squared <- (b_sp/b_ph)^2

nRed <- 5
nRow <- NROW(my_data)

nSample_var <- 1000000
nSample_mc <- 1000

Cl<-my_data[,2:length(my_data)]#suppose cl=var(alm)
Cl_sp <- array(0, dim=c(nRow,nRed))
Cl_ph <- array(0, dim=c(nRow,nRed))
length(Cl)
for (i in 1:length(Cl)) {
  #(shape/rate) convention : 
  Cl_sp[,i] <-(Cl[, i] * ratio_squared[i])
  Cl_ph[,i] <- (Cl[, i])
}
L <- array_2D[,1]
L <- 2*(array_2D[,1])+1

# Weighted sum of Chi squared distribution
y3_1<-array(0,dim=c(nSample_var,nRed));y3_2<-array(0,dim=c(nSample_var,nRed));y3<-array(0,dim=c(nSample_var,nRed));
  for (i in 1:nRed) {
    for (j in 1:nRow) {
      # Try to summing all the random variable
      y3_1[,i] <- y3_1[,i] + Cl_sp[j,i] * rchisq(nSample_var,df=L[j])
      y3_2[,i] <- y3_2[,i] + Cl_ph[j,i] * rchisq(nSample_var,df=L[j])
    }
    y3[,i] <- y3_1[,i]/y3_2[,i]
  }

print(paste0('n=',nSample_mc*nSample_var))
for (i in 1:nRed) {
  # compute the standard deviation of the ratio by Monte-Carlo
  print(paste0('red=',i,',mean_fid = ', ratio_squared[i],',mean_exp = ', mean(y3[,i])))
  print(paste0('numerator : var = ', var(y3_1[,i]), ', sigma = ', sd(y3_1[,i])))
  print(paste0('denominator : var = ', var(y3_2[,i]), ', sigma = ', sd(y3_2[,i])))
  print(paste0('var = ', var(y3[,i]), ', sigma = ', sd(y3[,i])))
}
print('#############################################################')
# par(mfrow=c(2,nRed))
color_curve <- c("red", "green", "grey", "black")

# Save PDF - Chisquare
pdf(file="Chisquare_Distribution.pdf")
for (i in 1:nRed) {
  if (i == 1) 
    plot(density(y3[,i]), col="blue", xlim=c(min(y3),max(y3)), main="z= 0.9595, 1.087, 1.2395, 1.45, 1.688")
  else 
    lines(density(y3[,i]), col=color_curve[i-1])
}
dev.off()

希望这能帮助您制作经典 R 绘图的 ggplot2 版本。

没有提供生成示例数据的代码,所以我使用了@akrun 之前使用的代码:y3 <- matrix(rnorm(5000), ncol = 5)

library(tidyverse)
as.data.frame(y3) %>%
    mutate(row = row_number()) %>%     # add row to simplify next step
    pivot_longer(-row) %>%             # reshape long
    ggplot(aes(value, color = name)) + # map x to value, color to name
    geom_density()