首页 > 解决方案 > 调整 Shiny RMarkdown 报告中的大图大小

问题描述

我正在开发一个闪亮的 RMarkdown 报告,其中包含一个部分,该部分允许用户通过基于不同变量(例如,主题、课程、作业)对数据集进行分组来创建不同的山脊线图。然而,一些变量只有几个组(例如主题),而其他变量有很多组(例如分配)。对于具有许多组的变量,结果图变得不可读,因此我想增加图形大小或允许用户以某种方式向下滚动图形。有没有人有任何建议我可以如何做到这一点?(下面带有虚拟数据的示例 Rmd 文件)

---
title: "Test"
author: "R User"
date: "9/7/2021"
output: html_document
runtime: shiny
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ggplot2)

# example data
df <- data.frame(
  subject = c(rep("A", 1000), rep("B", 1000), rep("C", 1000)),
  course = rep(paste0("Course ", as.character(1:300)), 10),
  value = rnorm(3000)
)
```

## Modify figure size

I would like to modify the figure size so the ridgelines are still readable when grouped by course, either by making the figure size larger overall or allowing the user to scroll down the figure.

```{r, echo=FALSE}
inputPanel(
  selectInput("group", label = "Group",
              choices = c("subject", "course"))
)

renderPlot({
  ggplot(df, aes(y = !!as.symbol(input$group), x = value)) +
    ggridges::geom_density_ridges(color = "grey95", fill = "grey50", alpha = 0.5) +
    geom_boxplot(fill = "grey95", color = "grey40", width = 0.2, outlier.shape = NA) +
    labs(y = "") +
    theme_minimal()
})
```

标签: rggplot2shinyr-markdown

解决方案


我们可以添加一个滑动条让用户选择情节的高度,这样当他们觉得太挤时,可以增加高度。

---
title: "Test"
author: "R User"
date: "9/7/2021"
output: html_document
runtime: shiny
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ggplot2)
library(shiny)
# example data
df <- data.frame(
  subject = c(rep("A", 1000), rep("B", 1000), rep("C", 1000)),
  course = rep(paste0("Course ", as.character(1:300)), 10),
  value = rnorm(3000)
)
```

## Modify figure size

I would like to modify the figure size so the ridgelines are still readable when grouped by course, either by making the figure size larger overall or allowing the user to scroll down the figure.

```{r, echo=FALSE}
inputPanel(
  selectInput("group", label = "Group",
              choices = c("subject", "course")),
  sliderInput("p_height", "Plot height", value = 600, min = 400, max = 1000, step = 50, round = TRUE)
)

renderPlot({
  ggplot(df, aes(y = !!as.symbol(input$group), x = value)) +
    ggridges::geom_density_ridges(color = "grey95", fill = "grey50", alpha = 0.5) +
    geom_boxplot(fill = "grey95", color = "grey40", width = 0.2, outlier.shape = NA) +
    labs(y = "") +
    theme_minimal()
}, height = exprToFunction(input$p_height))
```

将默认值更改为所需的数字valuemin max以像素为单位。

在此处输入图像描述


推荐阅读