I am working on a document and am using both knitr and ggplot2. I am new to knitr and TeX itself and therefore not overly familiar with all that I am doing.
When I open RStudio to do the work, I first run the following two commands:
require("knitr")
require("ggplot2")
I then click on the Compile PDF. I have the following code that throws an error:
<<histogram, echo=FALSE, fig.align='center'>>=
summary(los$hosp_svc)
summary(los$Pt_Age)
binsize = diff(range(los$Pt_Age)/30)
ggplot(los, aes(x = Pt_Age)) +
geom_histogram(binwidth = binsize, fill = "red",
alpha = 0.315, colour = 'black') +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank()) +
xlab("Patient Age in Years") +
ylab("Frequency/Count") +
ggtitle("Histogram of Patient Age")
#
The error that I am getting is that the ggplot function could not be found, which is odd because if I just run the above code in the console the graph produces just find, so I know the package is loaded and available for use.
Any thoughts?
Thank you,
When working with .Rnw files (or .Rmd files), be sure to include any library calls in your script (see below). When you press the "Compile PDF" button, the R code in your script is submitted to a new instance of R to prevent anything in your current environment from mucking up the results. This might seem a little strange, but is good for reproducibility. So objects that aren't created explicitly via your script and packages that aren't called explicitly in your script will be forgotten as soon as you hit "Compile PDF"
<<histogram, echo=FALSE, fig.align='center'>>=
library(ggplot2)
summary(los$hosp_svc)
summary(los$Pt_Age)
binsize = diff(range(los$Pt_Age)/30)
ggplot(los, aes(x = Pt_Age)) +
geom_histogram(binwidth = binsize,
fill = "red",
alpha = 0.315,
colour = 'black') +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank()) +
xlab("Patient Age in Years") +
ylab("Frequency/Count") +
ggtitle("Histogram of Patient Age")
#
Related
[WARNING] Deprecated: --self-contained. use --embed-resources --standalone
! Missing $ inserted.
<inserted text>
$
l.100 ![](methods_
files/figure-latex/plot-1.pdf)<!-- -->
Try to find the following text in methods.Rmd:
![](methods_
You may need to add $ $ around a certain inline R expression `r ` in methods.Rmd (see the above hint). See https://github.com/rstudio/rmarkdown/issues/385 for more info.
Error: LaTeX failed to compile methods.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See methods.log for more info.
Execution halted
I get this error message when I try to knit my methods section document. Everything seems to work fine if I delete the following code chunk:
#Overlaying both groups to see which questions show most differences in performance between them
ggplot(mapping = aes(x, y)) +
geom_bar(data = nonrankedplayers, aes(x= questions , y=scoreNR), width = 0.8, stat = 'identity', fill= 'darkgrey') +
geom_bar(data = rankedplayers, aes(x= questions , y=scoreR), width = 0.4, stat = 'identity') +
theme_classic() +
ggtitle("Percentage of participants knowing the answer per group")+
theme(plot.title = element_text(hjust = 0.5))+ #centre the title
scale_x_discrete("Question", breaks = seq(0,26, by = 1) )+
scale_y_continuous("Percentage correct", breaks = seq(0,1, by = 0.1))
I tried adding $ between the code chunk, but then R does not recognise it.
We've been trying to include a graphic of our plot(s) in the R markdown presentation, but it simply does not work. The code is working and we can see the plot in Rscript and the markdown report, but it doesn't work in the knitted presentation. We used the following code:
Boxplot {#plots .flexbox .vcenter}
a <- boxplot(student$bmi, col = "lightgreen",
main = "BMI allgemein",
col.main = "darkgreen",
ylab = "BMI (in kg/m^2)",
ylim = c(0,40))
a
as well as a ggplot
GGPlot
student %>%
ggplot(aes(x= Bewegung1, y=bmi, fill= Geschlecht)) +
geom_boxplot() +
ggtitle("Geschlechterspezifische Verteilung des BMI in Abhängigkeit von der Bewegung") +
theme(plot.title = element_text(hjust = 0.5)) +
stat_summary(fun = mean, colour = "darkblue", geom = "point",
shape=18, size=3, show.legend = FALSE) +
scale_y_continuous(breaks = seq(0,40, by = 5)) +
labs(x="Selbsteinschätzung der Bewegung in den letzten 7 Tage (60 min/day)", y="BMI")
We've tried adding different libraries (like httpuv) as suggested in other forums, but this doesn't work for us. We added the libraries ggplot2, tidyverse, ggtheme, foreign, dplyr and others (not relevant for this code).
We've also tried adding plot() as well as print() after the code and we've also looked at other presentation where it worked, did the exact same thing, but it didn't work for our presentation.
We're completely lost. Please help.
The output is shown like this
I have found R's default plots to be poorly aliased. As a solution, I set Cairo as the graphics device, and now the plots look much better.
Unfortunately, using Cairo has created another issue, which is that for some reason, I am not able to apply the font that I was using when the graph was displayed in the plot window (in the left-hand diagram above, Cambria is used, but the right-hand diagram fails to apply this font).
Here is my code:
library(readxl)
library(scales)
library(ggplot2)
library(dplyr)
library('Cairo')
windowsFonts(Cam = windowsFont("Cambria"))
dataset <- read_excel('CW Data.xlsx')
colnames(dataset)[4] <- "Broadband Subs (%)"
options(scipen = 1000)
# Scatter plot FDI~GDP with regression line
CairoWin()
ggplot(dataset, aes(x=`2019 GDP ($bn)`, y=`2019 FDI ($m)`)) +
geom_point(size=3, shape=1) +
geom_smooth(method='lm',formula=y~x, se=FALSE, color='black') +
scale_x_continuous(label = comma) + scale_y_continuous(label=comma) +
theme(panel.background = element_rect(fill="peachpuff"),
plot.background = element_rect(fill="peachpuff")) +
theme(panel.grid.major = element_line(colour = "gray72"),
panel.grid.minor = element_line(colour = "gray72")) +
theme(text = element_text(family = "Cam"))
ggsave("FDI~GDP.png", device="png", type = "cairo")
And here is a OneDrive link for the Excel data that I am using
https://1drv.ms/x/s!AvGKDeEV3LOs4gNr714Ie0KbOjhO?e=bkdPvk
I suggest you have a look at the packages ragg and systemfonts. They make working with fonts extremly easy and the results are better than the output of the base options.
First, I suggest you query all available fonts using View(systemfonts::system_fonts()). You can select every font present here and use it for plotting or saving a plot.
I recreated your plot using a built in dataset as the onedrive link you shared was broken. I used the Cambria font like this.
plot <- ggplot(dataset, aes(x = mpg, y = hp)) +
geom_point(size = 3, shape = 1) +
geom_smooth(
method = 'lm',
formula = y ~ x,
se = FALSE,
color = 'black'
) +
scale_x_continuous(label = comma) +
scale_y_continuous(label = comma) +
labs(x = "2019 GDP ($bn)", y = "2019 FDI ($m)") +
theme(
panel.background = element_rect(fill = "peachpuff"),
plot.background = element_rect(fill = "peachpuff")
) +
theme(
panel.grid.major = element_line(colour = "gray72"),
panel.grid.minor = element_line(colour = "gray72")
) +
theme(text = element_text(family = "Cambria")) # relevant line
I prefer saving the plot in an object and passing it explicitly to the save function.
ggsave(
"FDI~GDP.png",
plot = plot,
device = ragg::agg_png, # this is the relevant part
width = 1920,
height = 1080,
units = "px"
)
Here is the result:
I would say it worked flawlessly. You can also use ragg as your graphics device in RStudio to make this more consistent. Have a look here.
If you want to output the plot to a PDF, you can use showtext to register system fonts with all newly opening graphics devices. So what you need to do is:
library(showtext)
showtext_auto()
ggsave(
"FDI~GDP.pdf",
plot = plot,
width = 1920,
height = 1080,
units = "px"
)
The plot below was generated in R (without any issue), using this code:
library(tidyverse)
library(extrafont)
loadfonts()
x <- rexp(100)
data.frame(info = x) %>%
ggplot() +
geom_histogram(aes(x = info), col = "red", fill = "red", alpha = 0.5) +
theme_minimal() +
theme(text = element_text(family="LM Roman 10"))
As you can see, the font of the plot is set to "LM Roman 10", which I was able to do thanks to this post and it works perfectly within R.
However when I try to place the image in a LaTeX document using RMarkdown, I get this error:
Quitting from lines 10-22 (min_example.Rmd)
Error in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y, :
invalid font type
Calls: <Anonymous> ... drawDetails -> drawDetails.text -> grid.Call.graphics
Además: There were 50 or more warnings (use warnings() to see the first 50)
Ejecución interrumpida
Here is the code for min_example.Rmd
---
title: "Untitled"
author: "Javier Rojas"
date: "2/9/2020"
output: pdf_document
---
```{r, echo=FALSE}
library(tidyverse)
library(extrafont)
loadfonts()
x <- rexp(100)
data.frame(info = x) %>%
ggplot() +
geom_histogram(aes(x = info), col = "red", fill = "red", alpha = 0.5) +
theme_minimal() +
theme(text = element_text(family="LM Roman 10"))
```
I am using a Mac computer running macOS High Sierra and R 3.6.1
Usually quite easy to solve. The problem should be, that the font is not installed in your computer.
You have to download the .otf file for the font e.g. (https://fonts2u.com/lmroman10-regular.font) and install it on your Operating System.
If you don't know how to do this, just google it (e.g. "install extra font Windows"), there are plenty of tutorials on it online.
-edit-
I was a little to quick - didn't realize the problem just comes from running it in rmarkdown. Try the following:
```{r, fig.showtext=TRUE, echo=FALSE}
library("tidyverse")
library("showtext")
x <- rexp(100)
font_add("LM Roman 10", regular = "lmroman10-regular.otf")
data.frame(info = x) %>%
ggplot() +
geom_histogram(aes(x = info), col = "red", fill = "red", alpha = 0.5) +
theme_minimal() +
theme(text = element_text(family="LM Roman 10"))
```
It's important that you add fig.showtext=TRUE, library("showtext") and font_add("LM Roman 10", regular = "lmroman10-regular.otf").
I just placed the .otf in my project folder - but I think you can also give it another path.
There exists a current new approach using showtext and showtextdb packages.
On Windows, install manually Latin Modern Roman font (.tff version) following these steps easy instructions https://tex.stackexchange.com/questions/55787/latin-modern-roman-for-ttf. After the installation, you can locate all your fonts in "C:/Windows/Fonts/" just in case.
Once it's already installed, try the following R code to see and example:
install.packages("showtext")
install.packages("showtextdb")
library(showtext)
library(showtextdb)
#set the name and file path
font_add(family = "lmroman10", regular = "C:/Windows/Fonts/lmroman10-regular-webfont.ttf")
showtext_auto()
library(ggplot2)
p = ggplot(NULL, aes(x = 1, y = 1)) + ylim(0.8, 1.2) +
theme(axis.title = element_blank(), axis.ticks = element_blank(),
axis.text = element_blank()) +
annotate("text", 1, 1.1, family = "lmroman10", size = 15,
label = "Text using new font")
I'm trying to create a graph (using quickplot) for each column of a data set and save it to a folder as a pdf -any advice would be much appreciated!
So far I've made a test data frame (before I try it with 500+ columns)
test.data <-cbind.data.frame(data$col_1,data$col_2,data$col_3)
Then I've tried to write a function to plot and save the graphs. I'm trying to make the graphs bar charts (with some title & color specifications) which show the count of the no. people in each category. So the columns typically consist of categorical data.
plot.graphs <- function(x) {
for(i in colSums(x)){
plots <- quickplot(i) +
geom_bar(color= "#6267c1", fill="#6267c1") +
labs(title= "i",
x="i",
y="Count") +
theme(help()
plot.title = element_text(colour = "#453694"),
axis.title = element_text(colour ="#453694"))
ggsave(plots,filename = "testplot",nm[1],".pdf",sep="")
print(plots)
}
}
plot.graphs(test.data)
However, this seems to come up with lots of errors so I don't think I'm doing it right.
Try wrapping your plot-code with a pdf() graphical device and dev.off(). pdf() will open a pdf graphical device, and store all graphics you generate in a file, until you close the graphical device with dev.off().
I can't test your code because I don't have the dataset, but try this:
pdf(file = 'test.pdf', onefile = TRUE, paper = 'special', height = 11, width = 8.5)
for(i in colSums(x)){
plots <- quickplot(i) +
geom_bar(color= "#6267c1", fill="#6267c1") +
labs(title= "i",
x="i",
y="Count") +
theme(help()
plot.title = element_text(colour = "#453694"),
axis.title = element_text(colour ="#453694"))
}
dev.off()
Also see: https://stat.ethz.ch/R-manual/R-devel/library/grDevices/html/pdf.html
Just in case this is helpful for anyone, the following script ended up working for me:
plot.auto <- function(data, list = as.list(colnames(data))){
df <- data
ln <- length(names(data))
for(i in 1:ln){
plot <- quickplot(na.omit(df[,i],main=names(df)[i])) +
geom_bar() +
labs(title= colnames((df[,i])),
x=colnames((df)[i]),
y="y axis title") +
# this makes the titles and text particular colours
theme(
plot.title = element_text(colour = "#455876"),
axis.title = element_text(colour ="#455467"),
# this puts the labels on an angle so they don't overlap
axis.text.x = element_text(angle = 30, hjust = 1))+
# this makes the title of the plot the same as the column name
ggtitle(colnames((df)[i])) +
geom_text(stat='count',aes(label=..count..),vjust=-0.3)
print(length(unique(df[,i])))
# this deletes any characters in the column names which will make saving
difficult
save_name1<- gsub("/","or",as.character(colnames(df)[i]))
save_name<- gsub("\\?","",save_name1)
#this tells you each title of the graph as the function runs
print(save_name)
#this saves each graph in a folder which must be in your Working Directory
eg. Auto_Plot_Folder (as a pdf) with the file the same as the column name
ggsave(plot,filename =
paste("Auto_Plot_folder/",save_name,".pdf",sep =""),device ="pdf")
}
}