r - 如何在 RMarkdown html 中为 ggplot 图添加水平滚动条

标签 r ggplot2 r-markdown knitr

我最近开始使用 RMarkdown 进行报告。我正在编写的一份具体报告包含从多年来进行的许多实验中获得的数据的表格和图表 - 快速更新和汇总数据。

虽然我找到了一种为表格(通过使用 Kable)和代码块输出添加滚动条/滚动框的方法,但我无法为绘图添加滚动条。大多数图都不大,这不是问题,但是对于一/两个图有很多类别,当浏览器窗口大小改变或使整个页面的宽度变大时,我需要不调整图的大小。理想情况下,如果可能,它应该具有特定的大小并位于固定宽度的滚动框中。

这是我正在尝试做的那种情节的一个例子。欢迎任何建议!

---
title: "Add horizontal scrol"
author: "KTy"
date: "9/21/2018"
output: html_document
---

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

## R Markdown
### Want to add horizontal scroll bar around a plot

```{r rnorm_box_violin}
set.seed(2300)
xdf1 <- data.frame(  var1 = rnorm(  10000 , mean = 5000 , sd = 10) , str1 = rep("a0",10000)  )

for ( x in 10:50 ){
  n <- sample(x = c(10,0.1) , size = 1)
  xdf2 <- data.frame( var1 = rnorm(  x*n*1000 , mean = 5000+(x/2) , sd = 10) , str1 = rep(paste0("a",x),x*n*1000))
  xdf1 <- rbind(xdf1,xdf2)
  }

plot1 <- ggplot(  data = xdf1  , aes( x = str1 , y = var1  ))  + 
  geom_violin(fill='grey90', scale = 'count', colour = 'grey70') + 
   geom_boxplot( width = 0.2 ,  alpha = 0.1 , colour = 'grey30')+
  theme_bw()+
  theme(axis.text.x =  element_text(angle = 45, hjust = 1 ,vjust = 1))
```
Produces this plot:
```{r plot_it , echo = FALSE, width = 20 , height = 7}
plot1
```

我在 Mac 上使用 RStudio。我希望我的要求是有道理的,如果有任何不清楚的地方,请发表评论,我可以尝试进一步解释。干杯,谢谢!

最佳答案

您可以将自定义 CSS 添加到您的 knitr 文档中:

    ...
    plot1 <- ggplot(  data = xdf1  , aes( x = str1 , y = var1  ))  + 
    geom_violin(fill='grey90', scale = 'count', colour = 'grey70') + 
    geom_boxplot( width = 1 ,  alpha = 0.1 , colour = 'grey30')+
    theme_bw()+
    theme(axis.text.x =  element_text(angle = 45, hjust = 1 ,vjust = 1))
```
<style>
  .superbigimage{
      overflow-x:scroll;
      white-space: nowrap;
  }

  .superbigimage img{
     max-width: none;
  }


</style>


This produces the plot with a special css class
<div class="superbigimage">
```{r plot_it , echo = FALSE, fig.width=20,fig.height=3}
plot1
```
</div>


This produces the plot with the default settings
```{r plot_it2 , echo = FALSE, fig.width=20,fig.height=3}
plot1
```

懒人图片:

enter image description here

关于r - 如何在 RMarkdown html 中为 ggplot 图添加水平滚动条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52448104/

相关文章:

从数据框中删除所有只有零的列或行

r - 是什么导致R脚本被杀死?

r - 在 R markdown HTML 文件中并排打印数字?

r - 如何更改图例符号(关键字形)以匹配绘图符号?

r - 组合上标和包含 < 符号的变量标签时使用 ggplot geom_text

r - 创建新的强调命令 R Markdown

r - 对列表中的数据框迭代函数,找到匹配项

c++ - 找不到-lMagick++-6.Q16

Rmarkdown : spacing between parragraph and image

r - 如何在 R markdown 中生成没有序言的 LaTeX 文件?