export::graph2office moves axis labels around - r

I have made plots in R (RStudio) with ggplot2. When I export them via export::graph2office, the labels are moved around. However, this only happens when I specify the font for the labels.
library (ggplot2)
library (export)
plot_data <- data.frame (a = runif (1:20), b = seq (1:20))
x11 (width = 3, height = 3)
ggplot (data = plot_data, mapping = aes (x = a, y = b)) +
geom_point () +
labs (x = "my x-label", y = "my y-label") +
theme (panel.background = element_blank(),
panel.border = element_rect (fill = NA, size = 0.7),
axis.ticks = element_line (color = "black", lineend = "round"),
axis.ticks.length = unit (2, "mm"),
axis.text = element_text (color = "black"),
plot.margin = unit(rep (0, 4), "cm"),
text = element_text (size=18,
family="ChantillyLH",
color = "black")
)
graph2office (file = "my_graph", type = "DOC")
Here, you can see the graph in R (to the right) and the exported graph in word (to the left):
The undesired behaviour is more obvious for the y-label in this example, but also the x-label is moved a bit. I wonder if there is a way to fix this.
The same happens when I specify another font family, for example family="Comic Sans MS":
EDIT: it even happens when no textcommand is given:

The answer probably is: yes, export::graph2office moves axis labels around (so do export::graph2pptand export::graph2doc). There is no way to fix this. If you want to style your graphs in R and export them as-is into Office, the export::graph2office function, unfortunately, is not your way to go. However, the function can of course be used as a quick-and-dirty option to produce editable office-graphs.
If your goal is to export graphs in a more reliable manner, CairoSVG might be a much better option (see my answer here: Producing a vector graphics image (i.e. metafile) in R suitable for printing in Word 2007).

Related

How to change color of "tile grout" in R waffle plot to match background

I'm trying to make a waffle plot to use dark mode. This involves changing both the background color and the color of the tile grout. I can't figure out how to do the tile grout.
I'm unable to do any of the normal operations to change the color:
counts <- c(a = 701, b = 1094, c = 1756)
waffle(counts,
rows=50,
size=0.75,
legend_pos="bottom") + theme(legend.key.size=unit(3, "mm"),
rect=element_rect(fill='black',
color='black'),
plot.background=element_rect(fill='black'),
strip.background = element_rect(colour=NA, fill=NA),
panel.background=element_rect(fill='black', color='black'))
There was a pull request to do this, but the person who made it deleted it. It seems like the color is set as a margin color on every tile, since if you increase the waffle function argument size to size=0, you get no tile grout:
How do I get the tile grout to be the same black as the background?
This seems pretty hacky, but you can edit what you need in a ggplot object before printing.
library('waffle')
counts <- c(a = 701, b = 1094, c = 1756)
x <- waffle(counts,
rows=50,
size=0.75,
legend_pos="bottom") + theme(legend.key.size=unit(3, "mm"),
rect=element_rect(fill='black',
color='black'),
plot.background=element_rect(fill='black'),
strip.background = element_rect(colour=NA, fill=NA),
panel.background=element_rect(fill='black', color='black'))
x$layers[[1]]$aes_params$colour <- 'black'
x
A more "ggplot way" would be something like editing/replacing the layer:
x %+replace% geom_tile(inherit.aes = TRUE, color = 'black')
but that does not work. I'm not sure if you can replace a layer in-place without messing up the order. But this is essentially what the hack does.

ggplot2 scale legend so it fits on page

Hi I'm looking for a way to scale a ggplot2's legend (independently of the plot and label sizes), and ideally an automated way to do this scaling so that it fits on the page.
It is very easy to scale the whole plot, including the legend, just by changing the output size but sometimes (especially if I am pasting the plots into a report at a fairly small size) I might need the axis sizes to be fairly large.
I can't find any way to scale the legend as a whole. The options seem to be to manually split it over several rows or to change each element of the legend independently (as I have attempted below); but some of these can be set using rel and some can't its hard to know what you'll end up with and it still looks a bit funny.
It seems strange to me that the default behaviour for ggplot2 is to allow legends to go off the page.
Basically I want the plot like this (which was made in paint using a combination of test.png and test2.png from my example below):
Ideally I'd like it if during the save process it figures out the plot widow and then applies some scaling automatically. Otherwise if I could scale down with a percentage that what be second best option.
Reprex of a simple example. WARNING it saves to a c:\temp folder
library(ggplot2)
testplot <- ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length, colour = Species))+
geom_point()+geom_hline(aes(yintercept = 6, colour = "example line"))+theme(legend.position = "bottom")
ggsave(testplot,filename = "C:/temp/test.png", width = 3, height = 3)
ggsave(testplot,filename = "C:/temp/test2.png", width = 6, height = 6)
test2 <- testplot + theme(legend.key.size = unit(0.5,"lines"), legend.text = element_text(size = rel(0.5)),
legend.title = element_text(size = rel(0.5)))+
guides(colour = guide_legend(override.aes = list(size = 0.6)))
ggsave(test2,filename = "C:/temp/test3.png", width = 3, height = 3)
Created on 2019-09-04 by the reprex package (v0.3.0)

Problem of different x-axis position when using grid.arrange and legend on bottom

I have to arrange two plots with same axes next to each other and did this with ggplot2 and grid.arrange. Because of a more tidy representation, the legends have to be placed bottom. Unfortunately some times the left plot has more legend entries than the right one and therefore needs a second line, yielding x-axes on different y positions. Therefore it does not only look untidy, the aim of being able to compare these plots is not fulfilled anymore.
Can anybody help?
plot_left <- some_ggplot2_fct(variable,left) +
theme(legend.position = "bottom")+
theme(legend.background = element_rect(size = 0.5, linetype="solid", colour ="black"))
plot_right <- some_ggplot2_fct(variable,right,f)+
theme(legend.position = "bottom")+
theme(legend.background = element_rect(size = 0.5, linetype="solid", colour ="black"))
# adjust y axis for more easy compare
upper_lim <- max(plot_Volume_right$data$value, plot_Volume_left$data$value)
lower_lim <- min(plot_Volume_right$data$value, plot_Volume_left$data$value)
plot_Volume_left <- plot_Volume_left + ylim(c(lower_lim, upper_lim))
plot_Volume_right <- plot_Volume_right + ylim(c(lower_lim, upper_lim))
# Arrange plots in grid
grid.arrange(plot_Volume_left, plot_Volume_right,
ncol = 2,
top = textGrob(strTitle,
gp = gpar(fontfamily = "Raleway", fontsize = 15, font = 2)))
In the picture you can see the result:
Do you now an easy way to solve this without too much change in code? (The underlying framework is quite large)

Extra spaces on labels including cyrillic symbols in ggplot2

I'm trying to make a simple plot in R using ggplot2. The data is stored in a dataframe with its column written in Russian. The problem is that the contents of the label is shifted from the right border of the latter. These extra spaces appeared whether the label names are defined explicitly (the code below) or implicitly from the dataframe column names.
ggplot(mtcars, aes(x = drat, y =mpg, color = cyl))+
geom_point() +
labs(color = "Русское название") +
theme(legend.background = element_rect(color = "black", linetype = "solid", size = 0.7),
legend.justification = c(1, 1),
legend.position = c(1, 1),
legend.title.align = 0)
The plot with the English title is depicted appropriately.
The encoding of the operational system is set as follows:
"LC_COLLATE=Russian_Russia.1251;LC_CTYPE=Russian_Russia.1251;LC_MONETARY=Russian_Russia.1251;LC_NUMERIC=C;LC_TIME=Russian_Russia.1251"
Is there a way to cope this problem?
I have faced the same issue when needed legend with cyrillic symbols. Looks like it is known issue reported in ggplot2 repo because of the default graphic device on Windows. Actually, if you would try to save your ggplot with ggsave, probably you won't get that issue.
I have not tried to save files by myself yet, but I have followed the reported issue and found some workaround specific for R studio here and it has worked for me, maybe it can solve your issue too. Sample code to run before plotting anything is:
trace(grDevices:::png, quote({
if (missing(type) && missing(antialias)) {
type <- "cairo-png"
antialias <- "subpixel"
}
}), print = FALSE)

How to manage x axis ticks when handling dynamic x asix through shiny (inside ggplot)

Following is my plot function,
I have used implemented code here and not a reproducible one, because I just want to know the concept of handling things here.
print(ggplot(subset(gg1,!is.na(var)), aes_string(x = "Day", y = var, group = "Mi")) +
geom_point(aes(color = factor(Mi)), size = 5, alpha = 0.7) +
#scale_x_continuous(breaks=pretty_breaks(n=10)) + #geom_smooth(stat= "smooth" , alpha = I(0.4), method="loess",color="grey", formula = y ~ x)
scale_color_manual("Mesocosm", values = c('#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#808080', '#800000' , '#008000', '#008080')) +
scale_y_continuous(breaks=pretty_breaks(n=10)) +
theme_bw() +
geom_line(data = (ggl), size = 0.5) +
theme (legend.position = "right", legend.title=element_text(size=14),
panel.border = element_rect(colour = "black"),strip.background = element_rect(fill="#CCCCFF"),
strip.text.x = element_text(size=14, face="bold"),axis.text.y = element_text(colour="grey20",size=13,face="bold"),
axis.text.x = element_text(colour="grey20",size=13,face="bold"),
axis.title.x = element_text(colour="grey20",size=20,face="bold"),
axis.title.y = element_text(colour="grey20",size=20,face="bold")) +
xlim(input$slider[1],input$slider[2]) +
scale_x_continuous(breaks=pretty_breaks(n=10)) )
I want to split the x asix ticks to accomodate more ticks on the x axis. this I can do using scale_x_continuous as shown in the above example. The result is fine and I get the ticks as I wanted.
What is ticks? A similar question can be found here: [Pretty Breaks][1]
But in the above implementation the dynamic x axis fails to do its operation,
Dynamic x axis: change the slider bar points to make the x axis to adjust automatically.
Next:
if I reverse the order of last two lines like
scale_x_continuous(breaks=pretty_breaks(n=10)) + xlim(input$slider[1],input$slider[2]) )
Then scale_x _continuous doesn't work saying "Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale." (Which eliminates the having many ticks as i intend of having ).
How can I implement both in this case. [Want to have dynamic x axis and also want to overwrite the predefined ticks and have more ticks.]
The overview can be seen in this pic.
![enter image description here][2]
The pic is showing even though the slider bar values are changed , the x axis is not adjusting that is because as I said the order of scale_x_continuous and xlim.
How Can I make both work?
I think limits in the scale_x_continous() function is what you want.
Replace:
xlim(input$slider[1],input$slider[2]) +
scale_x_continuous(breaks=pretty_breaks(n=10)) )
With:
scale_x_continuous(breaks=pretty_breaks(n=10), limits=c(input$slider[1],input$slider[2])) )

Resources