r - 如何在 Shiny 应用程序中将 corrplot 图保存为 PDF?
问题描述
我正在尝试将 corrplot 的输出保存到 PDF 文件,并可以选择为其提供唯一的文件名。当我单击下载按钮时,它会在我的 PDF 查看器中打开 PDF 并为其分配一个随机文件名 - 欢迎任何帮助,因为我是一个完整的新手并且已经使用了一周。
这是代码 - 在代码下载部分的底部。
library(shiny)
library(shinythemes)
library(psych)
library(corrplot)
library(RColorBrewer)
library(Cairo)
library(grDevices)
# Correlation plot app with FDR option, which takes a CSV file
# containing species OTUs/ASVs and metabolites or clinical data
# see corrplot_test_data.csv
# Define UI for data upload app
# this section deals with the user interface (UI)
# and its design and format ----
not_sel <- "Not Selected"
about_page <- tabPanel(title = "About",
titlePanel("About"),
br(), "Correlation plot for species and metadata with False discovery rate adjustment")
instruction_page <- tabPanel(title = "Instructions",
titlePanel("Instructions"),
h4 ("Make sure all your inpit files are Comma seperated variable files (CSV)",
br(),
"Your input file needs to be in the format of Columns = species and variables (metabolite concs) and Rows = samples and as a CSV file",
br(),
"Your input file must not have any hyphens - or spaces in any of the rows and column headers and names.",
br(),
" Follow the running order i.e. start at 1 and then move to 2 etc",
br(),
"When you've finished click on the Analysis tab to see your plot"))
#ui <- fluidPage(
# App title ----
#titlePanel("Uploading Files"),
# Sidebar layout with input and output definitions ----
main_page <- tabPanel(title = "Analysis", titlePanel("Analysis"),
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Select number of rows to display ----
# radioButtons("disp", "1: What do you wish to display in the files?",
# choices = c(Head = "head",
# All = "all"),
# selected = "head"),
# Input: Select distance method ----
radioButtons("dist", "1: Select Distance method for Correlation",
inline = TRUE,
choices = c(Spearman = "spearman",
Pearson = "pearson",
Kendall = "kendall"),
selected = ";"),
# Input: Select FDR method ----
radioButtons("adjust_method", "2: Select false discovery rate adjustment method for Correlation",
inline = TRUE,
choices = c(Holm = "holm",
Hochberg = "hochberg",
Hommel = "hommel",
Bonferroni = "bonferroni",
Benjamini_Hochberg = "BH",
Benjamini_Yekutieli = "BY",
FDR = "fdr",
Pearson = "pearson",
Kendall = "kendall",
None = "none"),
selected = ";"),
# Input: Select display method ----
radioButtons("shape", "3: Select the shape of the symbol in your plot",
inline = TRUE,
choices = c(Circle = "circle",
Square = "square",
Ellipse = "ellipse",
Number = "number",
Shade = "shade",
Colour = "color",
Pie = "pie"),
selected = ";"),
# Input: Select layout for matrix ----
radioButtons("layout", "4: Select the layout of your plot",
inline = TRUE,
choices = c(Full = "full",
Upper = "upper",
Lower = "lower"),
selected = ";"),
# Input: Select ordering of the correlation matrix ----
radioButtons("reordered", "5: Select the layout of your plot",
inline = TRUE,
choices = c(AOE = "AOE",
First_principal_component = "FPC",
Alphabet = "alphabet",
Hclust = "hclust"),
selected = ";"),
# Input: Select ordering of the correlation matrix ----
radioButtons("hclust_method", "6: Select the Hclust method if you chose this in 5",
inline = TRUE,
choices = c(Ward = "ward",
Single = "single",
Complete = "complete",
McQuitty = "mcquitty",
Median = "median",
Centroid = "centroid"),
selected = ";"),
# Size of labels in plot line ----
sliderInput("text_size", "Text size for labels:",
min = 0.05,
max = 2,
value = 0.5),
# Size of labels in plot line ----
sliderInput("number_size", "Text size for correlation coefficient when Number is chosen in 3:",
min = 0.01,
max = 2,
value = 0.5),
# Input: Select number of rows to display ----
radioButtons("disp", "What do you wish to display in the Input data matrix panel?",
choices = c(Head = "head",
All = "all"),
selected = "head"),
# Input: Select file 1 for Input data into corr.test ----
fileInput("file1", "6: Choose Input data CSV File",
multiple = TRUE,
accept = c("text/csv","text/comma-separated-values,text/plain",".csv")),
# Download the plot ----
downloadButton('downloadPlot','Download Plot'),
tags$hr(),
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Data file ----
tabsetPanel(
tabPanel(title = "Input data matrix", tableOutput("shared")), # first panel
tabPanel(title = "Correlation plot", plotOutput("corr_plot")) # second panel
)
#tableOutput("metadata")
)
)
)
# Define server logic to read selected file
# this section deals with the functions and
# analysis that will be performed in the
# the app e.g. plots---
server <- function(input, output) {
options(shiny.usecairo=T)
output$shared <- renderTable({
# input$file2 will be NULL initially. After the user selects
# and uploads a file, head of that data file by default,
# or all rows if selected, will be shown.
req(input$file1)
df <- read.csv(input$file1$datapath,
header = TRUE,
sep = ',' ,
quote = input$quote)
if(input$disp == "head") {
return(head(df))
}
else {
return(df)
}
})
output$corr_plot <- renderPlot({
req(input$file1)
# take CSV file of OTU data and make PCoA class for plotting
rawdata <- read.csv(input$file1$datapath,header=T,row.names=1)
mat <- as.data.frame(rawdata)
# create correlation matrix
corr_mat <- corr.test(mat,
use = "pairwise",
method=input$dist,
adjust=input$adjust_method,
alpha=.05,
ci=TRUE,
minlength=5)
corr_r_values <- corr_mat$r
corr_p_values <- corr_mat$p
# set colour palette for heatmap
col=brewer.pal(n=11, name="RdYlBu")
#plot heatmap of correlation matrix
corrplot(corr_r_values,
method = input$shape,
col=rev(col),
type = input$layout,
hclust.method = input$hclust_method,
order = input$reordered,
p.mat = corr_p_values,
sig.level = 0.05,
insig = "blank",
addgrid.col = "#D3D3D3", # adjust for grid colour
tl.cex= input$text_size, # adjust for text size
number.cex = input$number_size, #adjust for number in plot size
pch.cex = "0.5", # input$text_size,
tl.col = "black", # adjust for text colour
diag = FALSE,
title=" ")
})
#download corrplot output as PDF file
output$downloadPlot <- downloadHandler(
filename = function(){paste(" ", '.pdf', sep = '')},
content = function(file){
cairo_pdf(filename = file,
width = 18, height = 10, pointsize = 12, family = "sans", bg = "transparent",
antialias = "subpixel",fallback_resolution = 300)
corrplot(corr_r_values,
method = input$shape,
col=rev(col),
type = input$layout,
hclust.method = input$hclust_method,
order = input$reordered,
p.mat = corr_p_values,
sig.level = 0.05,
insig = "blank",
addgrid.col = "#D3D3D3", # adjust for grid colour
tl.cex= input$text_size, # adjust for text size
number.cex = input$number_size, #adjust for number in plot size
pch.cex = "0.5", # input$text_size,
tl.col = "black", # adjust for text colour
diag = FALSE,
title=" ")
dev.off()
},
contentType = "application/pdf"
)
}
# Run the app ----
ui <- navbarPage(title = "PCoA creator",theme = shinytheme('cerulean'),instruction_page,main_page,about_page)
shinyApp(ui = ui, server = server)
解决方案
我就是这样做的
library(shiny)
library(shinythemes)
library(psych)
library(corrplot)
library(RColorBrewer)
# Correlation plot app with FDR option, which takes a CSV file
# containing species OTUs/ASVs and metabolites or clinical data
# see corrplot_test_data.csv
# Define UI for data upload app
# this section deals with the user interface (UI)
# and its design and format ----
not_sel <- "Not Selected"
about_page <- tabPanel(title = "About",
titlePanel("About"),
br(), "Correlation plot for species and metadata with False discovery rate adjustment")
instruction_page <- tabPanel(title = "Instructions",
titlePanel("Instructions"),
h4 ("Make sure all your inpit files are Comma seperated variable files (CSV)",
br(),
"Your input file needs to be in the format of Columns = species and variables (metabolite concs) and Rows = samples and as a CSV file",
br(),
"Your input file must not have any hyphens - or spaces in any of the rows and column headers and names.",
br(),
" Follow the running order i.e. start at 1 and then move to 2 etc",
br(),
"When you've finished click on the Analysis tab to see your plot"))
#ui <- fluidPage(
# App title ----
#titlePanel("Uploading Files"),
# Sidebar layout with input and output definitions ----
main_page <- tabPanel(title = "Analysis", titlePanel("Analysis"),
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Select distance method ----
selectInput("dist", "1: Select Distance method for Correlation:",
list(`Distance Method` = list("spearman", "pearson", "kendall"))
),
# Input: Select FDR method ----
selectInput("adjust_method", "2: Select false discovery rate adjustment method for Correlation:",
list(`Adjustment Method` = list("holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "pearson" , "kendall", "none"))
),
# Input: Select display method ----
selectInput("shape", "3: Select the shape of the symbol in your plot",
list(`Shape` = list("square", "ellipse", "number", "shade", "color", "pie"))
),
# Input: Select layout for matrix ----
selectInput("layout", "4: Select the layout of your plot",
list(`Layout` = list("full", "upper", "lower"))
),
# Input: Select ordering of the correlation matrix ----
selectInput("reordered", "5: Select the layout of your plot",
list(`Ordering of data` = list("AOE", "FPC", "alphabet", "hclust"))
),
# Input: Select ordering of the correlation matrix ----
selectInput("hclust_method", "6: Select the Hclust method if you chose this in 5",
list(`Clustering method` = list("ward", "single", "complete", "mcquitty", "median", "centroid"))
),
# Size of labels in plot line ----
sliderInput("text_size", "Text size for labels:",
min = 0.05,
max = 2,
value = 0.5),
# Size of labels in plot line ----
sliderInput("number_size", "Text size for correlation coefficient when Number is chosen in 3:",
min = 0.01,
max = 2,
value = 0.5),
# Input: Select number of rows to display ----
radioButtons("disp", "What do you wish to display in the Input data matrix panel?",
choices = c(Head = "head",
All = "all"),
selected = "head"),
# Input: Select file 1 for Input data into corr.test ----
fileInput("file1", "6: Choose Input data CSV File",
multiple = TRUE,
accept = c("text/csv","text/comma-separated-values,text/plain",".csv")),
# Height slider bar
sliderInput(inputId = "plot_height",
label = "Plot heigth",
min = 200, max = 1000, step = 10, value = 400),
# Width slider bar
sliderInput(inputId = "plot_width",
label = "Plot width",
min = 300, max = 1500, step = 10, value = 500),
# Download the plot ----
downloadButton('dbtn','Download Plot'),
tags$hr(),
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Data file ----
tabsetPanel(
tabPanel(title = "Input data matrix", tableOutput("shared")), # first panel
tabPanel(title = "Correlation plot", plotOutput("corr_plot", width = "100%", height ="100%")) # second panel
)
#tableOutput("metadata")
)
)
)
# Define server logic to read selected file
# this section deals with the functions and
# analysis that will be performed in the
# the app e.g. plots---
server <- function(input, output) {
output$shared <- renderTable({
# input$file2 will be NULL initially. After the user selects
# and uploads a file, head of that data file by default,
# or all rows if selected, will be shown.
req(input$file1)
df <- read.csv(input$file1$datapath,
header = TRUE,
check.names = FALSE,
sep = ',' ,
quote = input$quote)
if(input$disp == "head") {
return(head(df))
}
else {
return(df)
}
})
# creates a plot object called plot_obj which can be rendered and downloaded
plot_obj <- reactive({
req(input$file1)
# take CSV file of OTU data and make PCoA class for plotting
rawdata <- read.csv(input$file1$datapath,header=T,row.names=1, check.names=FALSE)
mat <- as.data.frame(rawdata)
# create correlation matrix
corr_mat <- corr.test(mat,
use = "pairwise",
method=input$dist,
adjust=input$adjust_method,
alpha=.05,
ci=TRUE,
minlength=5)
# extract correlation values from corr_mat
corr_r_values <- corr_mat$r
# extract p values from corr_mat
corr_p_values <- corr_mat$p
# set colour palette for heatmap
col=brewer.pal(n=11, name="RdYlBu")
#plot heatmap of correlation matrix
corrplot(corr_r_values,
method = input$shape,
col=rev(col),
type = input$layout,
hclust.method = input$hclust_method,
order = input$reordered,
p.mat = corr_p_values,
sig.level = 0.05,
insig = "blank",
addgrid.col = "#D3D3D3", # adjust for grid colour
tl.cex= input$text_size, # adjust for text size
number.cex = input$number_size, #adjust for number in plot size
pch.cex = "0.5", # input$text_size,
tl.col = "black", # adjust for text colour
diag = FALSE,
title=" ")
})
# this part renders the plot object for presentation in the appropriate panel
#data$Group <- env_data[[input$sel]]
output$corr_plot <- renderPlot({req(plot_obj())}, height = exprToFunction(input$plot_height), width = exprToFunction(input$plot_width))
#download corrplot output as PDF file
output$dbtn <- downloadHandler(
filename = function(){paste(" ", '.pdf', sep = '')},
content = function(file) {
pdf(file)
#corrplot(plot_obj())
req(input$file1)
# take CSV file of OTU data and make PCoA class for plotting
rawdata <- read.csv(input$file1$datapath,header=T,row.names=1, check.names = FALSE)
mat <- as.data.frame(rawdata)
# create correlation matrix
corr_mat <- corr.test(mat,
use = "pairwise",
method=input$dist,
adjust=input$adjust_method,
alpha=.05,
ci=TRUE,
minlength=5)
# extract correlation values from corr_mat
corr_r_values <- corr_mat$r
# extract p values from corr_mat
corr_p_values <- corr_mat$p
# set colour palette for heatmap
col=brewer.pal(n=11, name="RdYlBu")
corrplot(corr_r_values,
method = input$shape,
col=rev(col),
type = input$layout,
hclust.method = input$hclust_method,
order = input$reordered,
p.mat = corr_p_values,
sig.level = 0.05,
insig = "blank",
addgrid.col = "#D3D3D3", # adjust for grid colour
tl.cex= input$text_size, # adjust for text size
number.cex = input$number_size, #adjust for number in plot size
pch.cex = "0.5", # input$text_size,
tl.col = "black", # adjust for text colour
diag = FALSE,
title=" ")
dev.off()
}
)
}
# Run the app ----
ui <- navbarPage(title = "PCoA creator",theme = shinytheme('cerulean'),instruction_page,main_page,about_page)
shinyApp(ui = ui, server = server)
推荐阅读
- numba - 如何在 Numba 中创建类型化的字典 where (key, value) = (str, list)
- pine-script - 查找本周内的第一个柱
- java - 如何在 Java 中合并两个不可变集。?
- python - Python凯撒密码如何解码特定句子?
- windows - 具有不同扩展名的 XCOPY 文件
- chef-infra - 文件更改文件名的刀环境
- python - AttributeError:“str”对象没有属性“items”;尝试遍历python中的for循环
- asp.net - 设置 ASP.NET 数据库连接池最大生命周期
- solid-principles - “每个类一个方法”是否过度使用单一职责原则?
- bash - 将 ping 与后台进程结合使用