【问题标题】:Line plots for several data using ggplot2 and save as pdf使用 ggplot2 绘制多个数据的线图并另存为 pdf
【发布时间】:2023-04-08 00:05:01
【问题描述】:

使用以下三个不同的数据集,

    mean=replicate(10,rnorm(10))        
    colnames(mean)=paste0(rep(c("x0","x1","x2","x3","x4"),2),"_c", rep(c(1:2), each=5))
    meanpos=replicate(10,rnorm(10))+1.5
    meanneg=replicate(10,rnorm(10))-1.5
    hcol=c(0,0.5,0,0.75,1.0,
           1.1,1.20,0,0.8,-0.025)#vector of size ncol(mean)

我可以使用以下 for 循环创建线图

par(mfrow=c(2,2))
for ( v in 1:ncol(mean)){
  plot(mean[,v], type = "l", 
       ylim = c(min(meanpos[,v],mean[,v]), 
                max(meanpos[,v],mean[,v])), 
       xlab = "sl no", ylab = "",main = colnames(mean)[v])
  abline(h=hcol[v], col="purple")
  lines(meanpos[,v], col="blue")
  lines(meanneg[,v], col="green")
}

每列有一个图,并用2 by 2 概述。这里有一些地块

如何使用 ggplot2 函数创建一个类似的图,每行都有一个图例并保存为 pdf 文件。

感谢任何帮助

【问题讨论】:

    标签: r pdf ggplot2 line


    【解决方案1】:

    如果你想使用ggplot2,你可以格式化数据如下。最好将数据从向量保存到数据帧,然后您可以将所有数据绑定到重塑,并使用构面而不是循环来获得所需的绘图。您可以从facet_wrap() 调整ncol 参数以定义矩阵结构。这里使用您提供的数据的代码。我还添加了拥有数据框和轻松使用ggplot2 函数的步骤:

    library(tidyverse)
    #Initial data
    set.seed(123)
    #Data
    mean=replicate(10,rnorm(10))        
    colnames(mean)=paste0(rep(c("x0","x1","x2","x3","x4"),2),"_c", rep(c(1:2), each=5))
    meanpos=replicate(10,rnorm(10))+1.5
    meanneg=replicate(10,rnorm(10))-1.5
    hcol=c(0,0.5,0,0.75,1.0,
           1.1,1.20,0,0.8,-0.025)#vector of size ncol(mean)
    

    我们将数据保存在数据框中并识别所有值:

    #Concatenate all in a dataframe
    df1 <- as.data.frame(mean) 
    #Data for intercepts
    hcol=c(0,0.5,0,0.75,1.0,
           1.1,1.20,0,0.8,-0.025)
    #Dataframe
    dfh <- data.frame(name=names(df1),hcol,stringsAsFactors = F)
    #Mean pos
    df2 <- as.data.frame(meanpos)
    names(df2) <- names(df1)
    #Mean neg
    df3 <- as.data.frame(meanneg)
    names(df3) <- names(df1)
    #Assign ids
    df1$id <- 'mean'
    df2$id <- 'mean pos'
    df3$id <- 'mean neg'
    #Rows
    df1$id2 <- 1:dim(df1)[1]
    df2$id2 <- 1:dim(df2)[1]
    df3$id2 <- 1:dim(df3)[1]
    #Bind
    dfm <- rbind(df1,df2,df3)
    

    使用整个数据,我们将其重塑为使用构面:

    #Pivot
    dfm %>% pivot_longer(cols = -c(id,id2)) -> dfm2
    

    现在,剧情:

    #Sketch for plot
    G1 <- ggplot(dfm2,aes(x=id2,y=value,group=id,color=id))+
      geom_line()+
      geom_hline(data = dfh,aes(yintercept = hcol),color='purple')+
      facet_wrap(.~name,scales='free')+
      xlab("sl no")+ylab("")+
      scale_color_manual(values = c('mean'='tomato','mean pos'='blue','mean neg'='green'))+
      theme_bw()+
      theme(legend.position = 'top')
    

    您可以将ggsave()另存为.pdf

    #Export
    ggsave(filename = 'Plot.pdf',plot = G1,width = 35,height = 20,units = 'cm')
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-04
      • 1970-01-01
      • 2014-06-18
      • 2016-01-02
      • 1970-01-01
      • 2013-08-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多