Text not displaying in ggplot2 plot using rpy2 magic - r

When I generate any ggplot2 plot using R magic in Jupyter Notebook, all text in the plot is rendered as little empty boxes.
My environment is running the notebook via Jupyter Hub on Ubuntu server. R magic is working great in general, with the goal of re-using some existing R code I have to output a Word Cloud via wordcloud package. However, when I generate any plot using ggplot2 any text is missing and all I see are small empty boxes.
library(ggplot2)
ggplot(mtcars, aes(x = drat, y = mpg)) +
geom_point()
see image here
The plot should show text on the axis labels but no text is displayed, just empty boxes.
Generating the same plot when running R from ssh terminal and saving it to disk (it's on a headless server) looks fine. Generating plot via pandas data frame in a different cell looks fine. So it seems related to rpy2? I'm stumped.
[EDIT]: in fact I see the same behavior using R kernel on this server, so it seems to not be specific to rpy2 / R magic.

I was able to solve this by installing all the needed packages via R install.packages() rather than conda. Next time I think I will avoid using conda for R packages altogether; this isn't the first time it has caused issues.

Related

how do I fix plot problem with R in Jupyter notebook? [duplicate]

My R was installed in a conda environment on Ubuntu 20.04.1 VM.
I was searching for this problem when i found this thread. I too am using RStudio from Anaconda, on Debian 10.0 (buster).
Try
par(family = "Arial")
or whichever font name before calling plot(). It worked for me.
Update > I still had problems with ggplot2 plots not displaying labels, like above. I tried the workaround of using showtext() instead of regular text rendering.
install.packages("showtext")
After it was installed,
library(showtext)
to load the library. Then simply call
showtext_auto()
followed by the ggplot(.....) + ... + etc. function and text was rendered alright within the plot. I did not load specific fonts using font_add(). Maybe because previously 'Arial' was loaded with par()

Julia Plots.jl Latex issue

Plotting in Julia has been a pain for me thus far. I do
using Plots.jl
Initially the plotting was fine, even with latex expressions. However, something must have changed (I don't know what), and now when I wish to plot something with latex expression in the axis or title, for example:
plot(
p1,p2,
layout=layout,
link=:y,#aligns y-axis gridlines
size = (800, 400),
xtickfontsize=15,ytickfontsize=15,
xlab="s " *L" [h^{-1}Mpc]",
ylab=L"|x_s^2\xi_l^{bisector ,(2)}(s)/\xi_l^{pp}(s)|")
I get the error message:
latex: major issue: So far, no MiKTeX administrator has checked for updates.
latex: failed to create a dvi file
Furthermore, my plots are not longer being shown in Jupyter notebook (although I save them, and when I look at what was saved, the plots are there, although with messed up Latex).
Is there any easy fix for this?
I have tried using PyPlots (and PyCall to call it from python) but seem to have an issue importing that. For now I would prefer to stick with pure Julia plotting libraries, and be able to use them with latex.

Flag to print plots [duplicate]

I have a strange issue with Rstudio: If a script calls ggplot2 functions to display a plot, then using Source to run the script does not produce the plots. If I select the whole script with Ctrl+A, then Run the current line or selection (Ctrl+Enter), then the plot does display. Likewise, typing plotting commands into the console produces correct output.
For example:
library(ggplot2)
p = ggplot(mtcars, aes(wt, mpg))
p + geom_point()
Will only produce output if pasted into console, not if sourced.
There are other questions about this, but neither is helpful:
ggplot2 ggsave function causes graphics device to not display plots falsely claims the issue is fixed in newer versions, it has not.
RStudio - ggplot not saving first plot when printing and saving multiple plots in a script was closed as a duplicate, yet not only is it not a duplicate, but the dev.off() workaround doesn't work ("Error in dev.off() : cannot shut down device 1 (the null device)")
How can I get Rstudio to display plots when a script is sourced? I am using Rstudio 0.98.1062 and R 3.1.1.
The solution is to explicitly call print() on ggplot object:
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
p <- p + geom_point()
print(p)
ggplot function returns object of class ggplot; ggplot2 works by overloading print function to behave differently on objects of class ggplot - instead of printing them to STDOUT, it creates chart.
Everything is working well in interactive mode, because R assumes that most of commands are run through print() function. This is for our convenience and allows us to type rnorm(1) and get any visible output. When Run current selection command is used (Ctrl+Enter), RStudio behaves as if each selected line was typed in interactive mode and run. You can verify that by checking your command history in Console pane after running few selected lines.
But this convenient mode is abandoned when file is read by source(). Since this function is intended to run (potentially long and computationally-expensive) R scripts, it is undesirable to pollute STDOUT with low-priority messages. That's why source() by default will output only error message. If you want anything else, you have to explicitly ask for that.
though it's a quite old question. I had the same problem and found a quick solution, if you want to use "source" button on R studio edit box.
you can simply turn on "source with echo" (Ctrl + Shift + Enter) and the plot shows as expected
I recently happened on this question and realized that the most up to date way is to call show(p) after creating the plot.
I found this question when searching a similar problem (plots not showing up in RStudio). I was trying to troubleshoot a complicated ggplot2 block by running it in parts, but couldn't get anything to show up in the plot window.
Reason: the tiff() function I opened earlier had not closed.
Solution: I ran dev.off() a few times until all my earlier tiff() functions completed, then I was able to create plots in RStudio and view the results in the plot window.
Another option is simply using plot(). When clicking on "Source" in Rstudio, it show the plot in the window like this:
library(ggplot2)
p = ggplot(mtcars, aes(wt, mpg))
p = p + geom_point()
plot(p)
# This pops when clicking on Source
source("~/.active-rstudio-document")
Output:

R effects plot displays OK on screen but generated pdf contains no pages

I am using the effects package in R to derive (and plot) the effects of a complicated linear model.
When I use allEffects(linearModel) I can see the results on screen and save it to a pdf file as usual. Since the model has many terms, the output is not useful as it stands.
Therefore I use effects(someTerm, linearModel) to focus on the terms of interest and the results on screen are what I need. However, when saving it to a pdf file, the file contains no useful output (though it does take up 3.5Kb of space). There is no error message from R at the console.
To ease understanding, I created a simple data set and a script for generating the effects plots, in the same way that I tried with the "real" model.
factorData.csv
A,B,C,y
a1,b1,c1,3
a1,b2,c1,4
a2,b1,c1,5
a2,b2,c1,6
a1,b1,c1,2
a1,b1,c2,3.5
a1,b2,c2,4
a2,b1,c2,5.1
a2,b2,c2,6.2
plotEffect.r
require(effects)
dataFile <- '/tmp/factorData.csv'
effectABfile <- '/tmp/effect_AB.pdf'
effectABCfile <- '/tmp/effect_ABC.pdf'
allEffectFile <- '/tmp/lm_eff.pdf'
df <- read.csv(file=dataFile,header=TRUE,sep=',')
linearModel <- lm(y~A*B*C,data=df)
lm_eff <- allEffects(linearModel)
pdf(file=effectABfile)
plot(effect('A:B',linearModel))
dev.off()
pdf(file=allEffectFile)
plot(lm_eff)
dev.off()
pdf(file=effectABCfile)
plot(Effect(c('A','B','C'),linearModel))
dev.off()
As you can see, I tried allEffects, effect and Effect; allEffects is the only one that works for me. Please note that the script assumes that the data is placed in /tmp/factorData.csv - you might need to change the path of course. I also randomised the order in which the plots are generated, with no effect.
I had a look elsewhere on stackoverflow and saving plots to pdfs fails was the closest but the advice there (to issue dev.off() after each plot to 'close' the pdf file) is something I do already, as seen in plotEffect.r.
I tried this script on 2 machines, each running Lubuntu 14.04.1 64-bit with R version 3.0.2 and the latest effects package installed within R using install.packages. The results were the same.
I would be very grateful for advice on how to fix the problem of saving (instances of) this plot type to a pdf.
Fix/workaround
As suggested by #Roland in the comments below, if you wish to save grid plots (such as the output from the effects plots in this instance) into pdf files, it is better/more reliable to generate the plots separately/manually (rather than in a script). It does not appear to be (as much of) an issue for base graphics or even ggplot2 graphics, where I for one have never encountered this problem/needed this workaround in the past. Thanks to #Roland for suggesting this fix!
#Roland also added that Sys.sleep() might help in scripts. Although it did not do so in my case, I discovered that it was possible to paste several such plotting commands and R would run them as a batch, saving the plots to pdf correctly. Therefore, I believe it should be possible to recover much of the benefits of running the script by taking these steps:
Use R to create the text representation of the pdf(), plot() and dev.off() triad of commands
The main script outputs this plotting command text (specific to each instance of a plot) to a file
Open the plotting command text in a text editor
Copy the entire contents of the commands file and paste it into the R console
Optionally, you may wish to use the command line in Step 3 and 4 - How can I load a file's contents into the clipboard? has useful advice.
This two stage procedure is a reasonable workaround, but arguably there should be no need for it.

ggplot plots in scripts do not display in Rstudio

I have a strange issue with Rstudio: If a script calls ggplot2 functions to display a plot, then using Source to run the script does not produce the plots. If I select the whole script with Ctrl+A, then Run the current line or selection (Ctrl+Enter), then the plot does display. Likewise, typing plotting commands into the console produces correct output.
For example:
library(ggplot2)
p = ggplot(mtcars, aes(wt, mpg))
p + geom_point()
Will only produce output if pasted into console, not if sourced.
There are other questions about this, but neither is helpful:
ggplot2 ggsave function causes graphics device to not display plots falsely claims the issue is fixed in newer versions, it has not.
RStudio - ggplot not saving first plot when printing and saving multiple plots in a script was closed as a duplicate, yet not only is it not a duplicate, but the dev.off() workaround doesn't work ("Error in dev.off() : cannot shut down device 1 (the null device)")
How can I get Rstudio to display plots when a script is sourced? I am using Rstudio 0.98.1062 and R 3.1.1.
The solution is to explicitly call print() on ggplot object:
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
p <- p + geom_point()
print(p)
ggplot function returns object of class ggplot; ggplot2 works by overloading print function to behave differently on objects of class ggplot - instead of printing them to STDOUT, it creates chart.
Everything is working well in interactive mode, because R assumes that most of commands are run through print() function. This is for our convenience and allows us to type rnorm(1) and get any visible output. When Run current selection command is used (Ctrl+Enter), RStudio behaves as if each selected line was typed in interactive mode and run. You can verify that by checking your command history in Console pane after running few selected lines.
But this convenient mode is abandoned when file is read by source(). Since this function is intended to run (potentially long and computationally-expensive) R scripts, it is undesirable to pollute STDOUT with low-priority messages. That's why source() by default will output only error message. If you want anything else, you have to explicitly ask for that.
though it's a quite old question. I had the same problem and found a quick solution, if you want to use "source" button on R studio edit box.
you can simply turn on "source with echo" (Ctrl + Shift + Enter) and the plot shows as expected
I recently happened on this question and realized that the most up to date way is to call show(p) after creating the plot.
I found this question when searching a similar problem (plots not showing up in RStudio). I was trying to troubleshoot a complicated ggplot2 block by running it in parts, but couldn't get anything to show up in the plot window.
Reason: the tiff() function I opened earlier had not closed.
Solution: I ran dev.off() a few times until all my earlier tiff() functions completed, then I was able to create plots in RStudio and view the results in the plot window.
Another option is simply using plot(). When clicking on "Source" in Rstudio, it show the plot in the window like this:
library(ggplot2)
p = ggplot(mtcars, aes(wt, mpg))
p = p + geom_point()
plot(p)
# This pops when clicking on Source
source("~/.active-rstudio-document")
Output:

Resources