【问题标题】:How to fix inconsistent display of plot in pdf and html generated by knitr如何修复由 knitr 生成的 pdf 和 html 中的绘图显示不一致
【发布时间】:2020-07-30 10:39:02
【问题描述】:

我正在使用 knitr 包在 R markdown 中编写文档,该包必须以 HTML 格式提供以供在线查看,以 pdf 格式提供以供离线阅读。在 html 和 pdf 文档中显示的绘图输出中存在一些不一致。

  1. 条形图图例未正确显示在 pdf 中
  2. 饼图图例与 pdf 中的图重叠

items <- c('Food', 'Clothing', 'House Rent', 'Education', 
           'Litigation', 'Conventional Needs', 'Miscellaneous')
familyA <-c(24,4,4,3,2,1,2)
familyB <-c(60,14,16,6,10,6,8)
df = data.frame(items, familyA, familyB)
familyAPerc <- prop.table(familyA) * 100
familyBPerc <- prop.table(familyB) * 100
df <- cbind.data.frame(items, familyA, familyAPerc, familyB, familyBPerc)
subdf <- df[, c(3,5)]
par(xpd=T, mar=c(5,4,1.4,0.2))
barplot(as.matrix(subdf),  width=c(0.4, 1.2), legend.text = df$items, cex.main=0.6,
    args.legend = list(x="bottom", ncol=4, cex=0.6, bty='n', inset=-0.2))

将 inset 更改为 -0.3 可修复 pdf 中的输出,但图例在 html 中被裁剪。

x <-  c(50, 30, 20,15,35)
labels <-  c("food","clothing","house rent","fuel & light", "miscellaneous")
piepercent<- round(100*x/sum(x), 1)
pie(x, labels = piepercent, main = "Pie Diagram",col = rainbow(length(x)))
legend("topright", labels, cex = 0.8, fill = rainbow(length(x)))

整个 R 项目在this github repo 上可用

如何在不花费数小时的情况下在 html 和 pdf 输出中获得正确的绘图显示?请帮忙。

【问题讨论】:

  • 我尝试在您的存储库中复制您的代码并获得了/fig/tablesketch.png is not available error 也许您没有将那个 .PNG 上传到存储库中?即使是 Rmarkdown 的先驱,谢益辉也说过,有时候最好的分辨率就是先渲染成 HTML,然后在网页浏览器中将 HTML 网页打印成 PDF。

标签: r r-markdown knitr


【解决方案1】:

它没有包含在您的问题中,但在您引用的 Github 存储库中,您有这个 YAML:

---
title: "Presentation of Data"
output:
  pdf_document: 
    keep_tex: yes
    fig_width: 4
    fig_height: 4
    fig_caption: yes
    toc: yes
  html_document: 
    toc: yes
---

这会将 PDF 的宽度和高度设置为 4 英寸,并在 HTML 中将其保留为默认值(即 7 x 7 英寸)。将它们设置为相同的大小,数字看起来会相同。

如果 7 x 7 太大,可以设置fig.width=7, out.width="57%", fig.height=7, out.height="57%",绘图会按原尺寸绘制,然后缩小到更小的尺寸。据我所知,您必须在块选项中执行此操作,而不是在 YAML 中,但您可以使用

将这些值设置为初始块中的默认值
knitr::opts_chunk$set(fig.width=7, out.width="57%", fig.height=7, out.height="57%")

在开始的设置块中。 (我选择 "57%" 将 7 英寸缩小到 4 英寸。为不同的尺寸选择不同的百分比。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-10
    • 2019-02-04
    • 2015-04-19
    • 1970-01-01
    • 2018-07-01
    • 1970-01-01
    • 2015-01-15
    • 2016-07-01
    相关资源
    最近更新 更多