How to save high-definition maps with tmap in R? - r

usually, to save maps in vector format with tmap I use the following command:
tmap_save(maps, filename = "maps.pdf",height = 8.27, width = 11.69)
However, the results are unsatisfactory in terms of image quality when I import the pdf file into the document. I would like to know if there is anything else I need to consider in order to do this correctly. Thank you.

+1 to mgrund's answer. Why do you need to save maps in vector format? If you are only pasting the figures in the word document, you can export as png, and use the 'dpi' argument in tm_save() to increase resolution for raster images.
tmap_save(maps, filename = "maps.png",height = 8.27, width = 11.69, dpi=600)

Related

How to load raw binary array data into Julia and display it?

I would like to load a raw image data (such as the .raw ones from http://eeweb.poly.edu/~yao/EL5123/SampleData.html) into Julia and display them.
Basically, I am looking for a way to load file into Julia as Array{xxx} type.
Any ideas?
Here is the code and along with the resulting plot:
using Plots, Images, HTTP
r = HTTP.request("GET", "http://eeweb.poly.edu/%7Eyao/EL5123/image/lena_gray.raw")
img = reshape(r.body, 512, 512)
v = rotr90(colorview(Gray, img./256));
Plots.plot(v)
savefig("lena.png")

How do I save a wordcloud as a .png using the wordcloud2 package in r?

I've created a wordcloud using the 'wordcloud2' package in r and I want to save the output as a .png (or really any image file). I know that I can just save the initial output as a .png and use that, but the data that the wordcloud uses changes every time the document is knit (the data is tweets gathered using the rtweet::search_tweet function), and I want the wordcloud to be updated with the same info.
I've tried using the webshot & htmlwidget packages to save the wordcloud as .png, but I always get a blank image. I've even changed the delay to 120 seconds to make sure that I gave the wordcloud enough time to load properly. The original wordcloud output is ~1.6 MB if the size might be a problem.
Here's my code:
library(wordcloud2)
library(webshot)
library(htmlwidgets)
Bcloud <-
wordcloud2(wordFreq,
size = 1,
figPath = "images/#Bv2.png",
color = colorVec)
Bcloud
#
saveWidget(Bcloud, "tmp.html", selfcontained = F)
webshot("tmp.html", "wordcloud.png", delay = 120, vwidth = 2000, vheight = 2000)
UPDATE: I removed figPath = "images/#Bv2.png" and changed the shape to one of the standard options (star, triangle, diamond, etc.) and now the wordcloud saves as a .png using saveWidget() and webshot(). I guess the issue is with the mask. The image I'm using for the mask is 13.1 KB.

Reading PDF plots, arranging them on a grid, save in one-page PDF using R

I have 3 R plots saved as pdf files (upper_left.pdf, upper_right.pdf, lower.pdf) as vector graphic and want to make a one-page pdf file and arrange them on it as follows:
What I have tried already
I have tried reading the pdf's using magick::image_read_pdf and appending them using magick::image_append. More specifically,
library(magick)
panel.ul <- image_read_pdf("upper_left.pdf")
panel.ur <- image_read_pdf("upper_right.pdf")
panel.l <- image_read_pdf("lower.pdf")
whole <- c(panel.ul, panel.ur) %>%
image_append() %>%
c(panel.l) %>%
image_append(stack = TRUE)
The first issue is magick::image_read_pdf imports the plot as png (if I'm right, not vector graphic though).
magick::image_append also 'works' and gives me what I want in viewer pane (in RStudio, next to Help).
I then try to save them using export::graph2pdf(whole), but it gives me a blank page.
So, if I am to use magick, there are two issues that need to be solved:
importing plots as vector graphic objects (do not know the technical term in R)
Exporting the stacked plot to a vector pdf file.
How can I solve it? thanks in advance.
You're basically done. You only need to add
plot(whole) # plot the external object generated in ImageMagick to R's plotting device
savePlot(type = "pdf") # saves the current plotting device to a pdf file.
You will find your plot in your workoing directory called "Rplot.pdf".
savePlot has many options to customize your pdf output. Make sure to check ?savePlot.
To recreate your scheme from above youll need to temporarily save the upper panel as a separate pdf before you paste it to on top of the lower panel:
whole2 <- image_append(c(panel.ul, panel.ur))
plot(whole2)
savePlot("whole2.pdf", type = "pdf")
If the upper and lower panel do not look proportionate you can use the heght and width parameters of savePlot to adjust the size of the first pdf.
panel.upr <- image_read_pdf("whole2.pdf")
final <- image_append(c(image_append(panel.upr),panel.l), stack = TRUE)
plot(final)
savePlot("final.pdf", type = "pdf")

How to increase resolution of ggplots when exporting using officer R

I want to export charts to a PPT and am using the officer package to achieve the same. However, the default resolution of the charts is low and I would like to change that. I am currently using the following call
ph_with_gg(p1,type = "chart",res = 1200)
where p1 is a ggplot object. On running this, I get the following error:
Error in png(filename = file, width = width, height = height, units =
"in", :
formal argument "res" matched by multiple actual arguments
Would really appreciate the help around this
Rather than using png, for high-resolution plots in PPT you should be using vector graphics.
See under extensions:
Vector graphics with package rvg
The package rvg brings an API to
produce nice vector graphics that can be embedded in PowerPoint
documents or Excel workbooks with officer.
This package provides functions dml() and ph_with() corresponding method to export ggplots to .pptx as vector graphics.
Example:
library(ggplot2)
library(officer)
library(rvg)
library(magrittr)
data(iris)
read_pptx() %>%
add_slide(layout='Title and Content',master='Office Theme') %>%
ph_with('Iris Sepal Dimensions', location = ph_location_type(type="title")) %>%
ph_with(dml( ggobj=
ggplot(iris, aes(x=Sepal.Length,y=Sepal.Width,col=Species)) +
geom_point()), location = ph_location_type(type="body")) %>%
print('iris_presentation.pptx')
As an additional benefit, you will be able to edit the charts in PowerPoint. For example, if you decided to capitalize the names of the 3 species, you could just edit the chart instead of editing the data and regenerating the slides. (You can also make the plots non-editable, but editable is the default.)
Is it important that the plot is saved to a presentation in the code?
Otherwise using:
ggsave(filename = file, p1, width = width, height = height, dpi = dpi)
will give you a png of any resolution you need..
(provided that filename ends with .png and you set width, height and dpi to appropriate values)

Generating PDF from multiple JPEGs in R

I have a folder with multiple JPEG files. How do I generate a PDF file from these JPEGs in R?
One JPEG = 1 PDF page. Images are of the same size.
Thanks a lot in advance.
You can do this easily using Latex. Which is nice, because then you can just use Sweave to do the whole thing.
You can do something along the lines of :
% This is some Sweave file
\documentclass{article}
\usepackage{graphicx}
\begin{document}
<<results=tex,echo=FALSE>>=
mypics <- dir('mypics')
for(i in mypics){
cat("\\includegraphics{", i, "}\n\n", sep = "")
}
#
\end{document}
OK, you'll have to set up your Sweave pipeline, but with a bit of tweaking you can automate the whole process easily.
if you insist on using R (other tools are more suitable), try something like this (slow, untested):
lf = list.files(pattern = "jpeg") # image filenames
library(jpeg)
jpegs = lapply(lf, readJPG)
library(grid)
pdf("output.pdf", width=8, height=4)
grid.raster(jpegs[[1]])
lapply(jpegs[-1], function(x) {grid.newpage() ; grid.raster(x)} ) -> bquiet
dev.off()
If you insist on using R to do this then you can open a pdf plotting device, par to set the margins (default will probably be to big and not centering), then in a loop use plot.new to start a new page and plot.window to set up the coordinates, etc. without plotting axes etc., use the read.jpeg function from the ReadImages package (or other tool/package to read, EBImage is another possibility) then rasterImage to plot the jpeg to the pdf device (or replace some of those steps with other image plotting functions, such as the plot method in ReadImages).
But overall it is probably easier/quicker/better/... to use a tool better designed for this type of thing. The ImageMagick suite of programs comes to mind, LaTeX has also been mentioned, and there are probably other tools as well.

Resources