Reputation: 2279
I am writing a document in R markdown using the knitr package, which has to be provided as HTML for online viewing and as pdf for offline reading. There are some inconsistencies in the output of the plots as shown in html and in the pdf document.
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))
Changing inset to -0.3 fix the output in the pdf but the legend is cropped in 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)))
The entire R project is available on this github repo
How can I get proper plot display in both html and pdf outputs without spending hours? Please help.
Upvotes: 0
Views: 909
Reputation: 44977
It wasn't included in your question, but in the Github repository you referenced, you had this 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
---
This sets the width and height to 4 inches for the PDF and leaves it at the default (which is 7 x 7 inches) in HTML. Set them both to the same size and the figures will look the same.
If 7 x 7 is too big, you can set fig.width=7, out.width="57%", fig.height=7, out.height="57%"
, and the plot will be drawn at full size, then shrunk to the smaller size. As far as I know you have to do this in chunk options, not in the YAML, but you can set those values as defaults in your initial chunk using
knitr::opts_chunk$set(fig.width=7, out.width="57%", fig.height=7, out.height="57%")
in the setup chunk at the beginning. (I chose "57%"
to shrink 7 inches to 4 inches. Pick a different percentage for a different size.)
Upvotes: 2