我正在使用plotly
R
包在我的shiny
应用程序中显示一些大图,图表显示效果很好。但是,当我单击“下载为png”按钮时,已下载的.png已调整大小。 here is a demo of this behavior
如何指定导出的绘图的分辨率?
这是一个最小的例子,它通过在下载时剪辑了一个很长的标题来证明这个问题
app.R
library(shiny)
library(ggplot2)
library(plotly)
ui <- fluidPage(titlePanel("Plotly Download demo"),
plotlyOutput("demoPlotly"))
server <- function(input, output) {
output$demoPlotly <- renderPlotly({
#make an arbritrary graph with a long title
p <- iris %>%
ggplot(aes(x = Petal.Length, y = Petal.Width, color = Species)) +
geom_point() +
labs(title = "This is a really long title to demo my problem of plotly resizing my downloaded output")
ggplotly(p)
})
}
# Run the application
shinyApp(ui = ui, server = server)
答案 0 :(得分:3)
迈克尔,
看看plotly_IMAGE()
。 [版本4.7.1]。该功能允许您指定保存图像的宽度和高度。例如800乘600。
关于您的示例,我提供了一个示例,说明如何修改布局以适应标题换行。请注意更改边距和填充。我还插入了对plotly_IMAGE
的调用以提供其使用的简化示例 - 它减慢了因为它与绘图生成一致。我建议您添加一个按钮并从图像显示中分离出来。
希望这有帮助
保重 吨。
要使用此示例示例,您需要注册并获取plotly api
密钥。获得后,您需要将这些条目添加到~/.Renviron
文件中。
参考:https://plot.ly/r/getting-started/
plotly_username="xxxxx"
plotly_api_key="xxxxxx"
library(shiny)
library(ggplot2)
library(plotly)
wrapper <- function(x, ...) {
paste(strwrap(x, ...), collapse = "\n")
}
# Example usage wrapper(my_title, width = 20)
my_title <- "This is a really long title to demo my problem of plotly resizing my downloaded output"
ui <- fluidPage(titlePanel("Plotly Download demo"), plotlyOutput("demoPlotly"))
pal <- c("blue", "red", "green")
pal <- setNames(pal, c("virginica", "setosa", "versicolor"))
layout <- list(title = wrapper(my_title, width = 60),
xaxis = list(title = "Petal Length"),
yaxis = list(title = "Petal Width"),
margin = list(l = 50, r = 50, b = 100, t = 100, pad = 4))
server <- function(input, output) {
output$demoPlotly <- renderPlotly({
# make an arbitrary graph with a long title
p <- iris %>%
plot_ly(x = ~Sepal.Length,
y = ~Petal.Width,
color = ~Species,
colors = pal,
mode = "markers",
type = "scatter") %>%
layout(autosize = F,
title = layout$title,
xaxis = layout$xaxis,
yaxis = layout$yaxis,
margin = layout$margin)
p$elementId <- NULL
# Example usage of plotly image
plotly_IMAGE(p,
width = 800,
height = 600,
format = "png",
scale = 1,
out_file = "output.png")
p
})
}
# Run the application
shinyApp(ui = ui, server = server)