Plots are squished when exporting to .pptx using officer - r

I'm using the officer package to write ggplots to Powerpoint, and even though my plots look good in my Rstudio viewer, my plots are getting "squished" when I add them to any custom slide with smaller content boxes.
I did my best to reproduce my issue with the following code:
library(tidyverse)
library(officer)
p <- data.frame(x = rnorm(100)) %>%
ggplot() +
geom_density(aes(x)) +
labs(title = "This is a title") +
annotate("text", x = 0, y = 0.2, label = "This is some text")
read_pptx("~/Downloads/template.pptx") %>%
add_slide(layout = "Title and Content") %>%
ph_with(p, location = ph_location_type("body", id = 1)) %>%
add_slide(layout = "text_example") %>%
ph_with(p, location = ph_location_type("body", id = 1)) %>%
print("~/Desktop/test_example.pptx")
Where template.pptx is a copy of the officer template with the "Title and Content" slide duplicated (and named "test_example") and content box shrunken down a little bit (available here for reproducibility).
The first slide looks good, like this:, but the second slide has the dimensions of the plot shrunken while the content in the plot stays the same size, giving it a "squished" feel:
Has anyone run into this before? Are there any tricks/hacks out there that can tell my plot to decrease the size of all it's elements when the total image space is decreased? I'd like to maintain the relative size of the elements of the plot as I move to different slide templates.
If you're still here - THANK YOU FOR READING SO FAR! I'd appreciate any and all tips :)

Here is the code that would avoid that problem with officer version 0.3.14 or later (I haven't update my package for a while and officer is an on-going package)
For better quality plot with smaller size using vector graphic instead. Using package rvg
library(rvg)
library(gridExtra)
document %<>%
add_slide(layout = "text_example") %>%
# add the plot in at position relative to 1 inches top left
# with size is 6 inches square
# grid.arrange is just a code for generate plot not actually arrange anything
ph_with(value = dml(code = grid.arrange(plot), bg = "transparent"),
location = ph_location(left=1, top=1, width=6,
height=6, bg="transparent")) %>%
# Add a text box on the right side of the slide with certain
# size & colors
ph_with(value = block_list(fpar(ftext(" "))),
location = ph_location(left=6.11, top=1, width=3.73,
height=3.3, bg="#C6D9F1"))
I would recommend this when working with Powerpoint otherwise, you need to adjust template in Powerpoint and remember the order of each content container in that slide

Related

Fixing spacing issue with annotations in cowplot/patchwork

I'm trying to combine several figures drawn in PowerPoint into a panel, using patchwork, cowplot, magick. However, I always feel that the distance between the annotation and the actual figure is too big, and I'm struggling to find a way that minimises the distance.
Is there a way to fix this issue?
Here's is my code.
library(patchwork)
library(cowplot)
library(magick)
# You can test with any other image, so the code should be reproduceable
design <- "./design.png"
courses <- "./courses.png"
# here I draw the figure using draw_image
design <- ggdraw() + draw_image(design, x = 0,
y = 0)
courses <- ggdraw() + draw_image(courses)
design / courses + plot_annotation(tag_levels = 'A')
A solution that fixed the problem was to use ggsave and playing around with the width and height, as suggested in the comments. For me, this one worked.
plot <- design / courses + plot_annotation(tag_levels = 'A')
ggsave("myplot.tiff", device = "tiff", height = "0.5")

Highlight a Specific Section of a Treemap using Treemap package in R

I am using the Treemap package in R to highlight the number of COVID outbreaks in different settings. I am making a number of different reports using R Markdown. Each one describes a different type of settings and I would like to highlight that setting in the treemap for each report, showing what proportion of total outbreaks occur in the setting in question. For example you I am currently working on the K-12 school report and would like to highlight the box representing that category in the figure.
I was previously using an exploded donut pie chart however there were two many subcategories and the graph became hard to read.
I am picturing a way to change the label or border on one specific box, ie. put a yellow border around the box or make the label yellow. I found a way to do both these things for all the boxes but not just one specific box. I made this image using the snipping tool to further illustrate what the desired outcome might look like. The code to generate the treemap can be found in the link below. It looks like this:
# library
library(treemap)
# Build Dataset
group <- c(rep("group-1",4),rep("group-2",2),rep("group-3",3))
subgroup <- paste("subgroup" , c(1,2,3,4,1,2,1,2,3), sep="-")
value <- c(13,5,22,12,11,7,3,1,23)
data <- data.frame(group,subgroup,value)
# treemap
treemap(data,
index=c("group","subgroup"),
vSize="value",
type="index"
)
This is the most straightforward information I can find about the package, this is where I took the sample image and code from: https://www.r-graph-gallery.com/236-custom-your-treemap.html
It looks like the treemap package doesn't have a built-in way to do this. But we can hack it by using the data frame returned by treemap() and adding a rectangle to the appropriate viewport.
# Plot the treemap and save the data used for plotting.
t = treemap(data,
index = c("group", "subgroup"),
vSize = "value",
type = "index"
)
# Add a rectangle around subgroup-2.
library(grid)
library(dplyr)
with(
# t$tm is a data frame with one row per rectangle. Filter to the group we
# want to highlight.
t$tm %>%
filter(group == "group-1",
subgroup == "subgroup-2"),
{
# Use grid.rect to add a rectangle on top of the treemap.
grid.rect(x = x0 + (w / 2),
y = y0 + (h / 2),
width = w,
height = h,
gp = gpar(col = "yellow", fill = NA, lwd = 4),
vp = "data")
}
)

ggplot2: CairoSVG changes point size

I build scatterplots using ggplot2 in R. I then want to save them as svg files with Cairo::CairoSVG. It seems to work fine except for the point size, which is enlarged in the resulting .svg file.
Here comes some example code:
library (ggplot2)
my_plot <- ggplot(mpg, aes(cty, hwy)) +
geom_point(size = 0.5)
x11 (width = 6, height = 6)
my_plot
Cairo::CairoSVG (file = "my_path",
width = 6, height = 6)
print (my_plot)
dev.off()
And this is what I get: on the right hand, the plot printed in R and on the left side the saved .svg-file opened in Inkscape. It looks fine except for the point size, which is a pity. Are there any ideas on how to get the right point-size? I tried different point sizes and also shapes, with similarly unmatched results.
Note that I seek to stick with Cairo::CairoSVG, beacuse in the final plots I wish to use custom fonts which are printed nicely with Cairo::CairoSVG. Any help is appreciated.
EDIT: I am working on a Windows machine.
Preliminary remark: when you pass width = 6, height = 6 in the Cairo::CairoSVG() parameters, you provide potentially different parameters (resolution and display) from the ones used in the RStudio plot panel.
To get the exact same image than the one rendered in the panel as well as using Cairo, you can use this alternative (dev.size('px') returns the dimensions of the current plot panel):
library (ggplot2)
my_plot <- ggplot(mpg, aes(cty, hwy)) +
geom_point(size = 0.5)
my_plot
mirror <- recordPlot()
png(filename = "mypath",
width = dev.size('px')[1]/96,
height = dev.size('px')[2]/96,
res = 96, # base RStudio resolution
units = "in",
type = "cairo") # calls CairoSVG
replayPlot(mirror)
dev.off()
(Note : I prefer the use of png() rather than ggsave() because it will save the entire last plot. I have observed that ggsave() would save only the last facet of a grid, for example)

r bokeh chart legend - placed poorly move

I have been working in flexdashboards using rbokeh to draw some dynamic graphs. Because this is a bar chart mapped to categorical data in the variable Classification, I am unable to manually create a legend, which is fine because rbokeh does it automatically.
However, I am having some issues with the legend and labeling:
It is placed horribly, I would like to tell r to place in the upper left hand corner to get it away from bars with content.
I would like to drop the red ab_line into the legend and label it (using standard legend = will not work because of the mapped variables in the base chart
This graph needs to be 508 compliant for translation, the flexdashboard is, as well as the bokeh tools on the left hand margin and the keys in the pop ups, but the values and labels remain in English. Does anyone have a way of making the charts responsive to google translate? I am fine if that involves editing the extruded page....I will just need more guidance in doing it there.
figure(title=" Confirmed & Probable Cases by Year",width= 1400, height
=350)%>%
ly_bar(x=Year, y= count, position='stack', data=probConf,
width=.9,hover=TRUE, legend=TRUE, color=Classification) %>%
x_axis(label ='Year')%>%
y_axis(label ='Cases')%>%
ly_abline(v=17.5, legend=NULL, color = "red", width =1, alpha=.5)%>%
[![enter image description here][1]][1]set_palette(discrete_color = pal_color(c("#ee9f00", "#ffcc66")))
To answer number 1, you can use legend_location to specify the placement of the legend (see example below and note I replaced the probConf data with the lattice barley dataset so that it is reproducible for others).
figure(title = " Confirmed & Probable Cases by Year", width = 1400,
height = 350, legend_location = "top_left") %>%
ly_bar(x = variety, y = yield, position = "stack", data = lattice::barley,
width = 0.9, hover = TRUE, legend = TRUE, color = year) %>%
x_axis(label = "Year") %>%
y_axis(label = "Cases") %>%
ly_abline(v = "Svansota:1", color = "red", width = 1, alpha = 0.5) %>%
set_palette(discrete_color = pal_color(c("#ee9f00", "#ffcc66")))
#2 is currently difficult to achieve in rbokeh but it should be more robust to situations like this (mixing mapped and user-defined legend entries) in the future. If ly_abline() were to accept data as an argument, you could use use a mapped variable for color to resolve the issue.
One solution that isn't very pretty is to manually draw the bar chart polygons with ly_rect (one call to ly_rect for each classification) and use custom legend entries for those and then add a custom legend entry for ly_abline.
I do not know the answer to #3.

R: background or inserted image and text in lattice

I'd like to insert a watermark onto a lattice image. In ggplot2, I simply used the the annotate or annotation_custom options to place a logo image and a text below the logo in a corner of the plot. Is there a similar possibility in lattice? Or as an alternative - is it possible to use an image as background of the plot?
This is what Deepayan Sarkar offered on Rhelp a couple of years ago to a similar question:
barchart(variety ~ yield | site, data = barley, groups = year, layout = c(3,1),
page = function(n) {
grid.text(label = "Privileged and Confidential \nDRAFT",
x = unit(0.01, "npc"),
y = unit(0.95, "npc"),
just = c("left", "center")) })
Obviously you would also need to use grid graphics functions to place the logo, (but you haven't offered one to work with. The first two lines of this next code was found at #baptiste's blog page cited today on SO.) The second two lines were adapted from Paul Murrell's article in last years "R Journal" found with Rseek.org:
library(png)
m <- readPNG(system.file("img", "Rlogo.png", package="png"), FALSE)
rimg <- as.raster(m)
grid.raster(rimg, x=.05, y=.9, just="top", width=.1)

Resources