degree symbol incorrect in map axis labels - r

If I create maps using geom_sf, the axis labels have the wrong symbol for degrees. I get degree symbols that are vertically centred in the text, rather than raised like superscipts.
For example,
library(sf)
library(ggplot2)
nc = st_read(system.file("shape/nc.shp", package="sf"))
ggplot() +
geom_sf(data = nc) +
theme(axis.text = element_text(size=16))
When I see examples online, they typically look correct (e.g. image below, copied from here), so I guess it is related to something in my local setup.
I have tried changing font, using library(extrafont) but this problem remains in every font I tried.
Update
I don't think this is a ggplot-specific issue, as I get the same thing with any graphics that uses the degree keyword in plotmath. For example
par(mar=c(0,0,0,0))
plot.new()
text(0.5,0.5, bquote(120*degree*N), cex=5)
I am on Linux (Kubuntu 19.04), R 3.5.2, ggplot2 v. 3.2.1, sf v. 0.7-7.
Not sure what other information might be relevant, but I can update answer with anything else that is requested.

Finally managed to track down the answer:
From ?X11 it says:
Problems with incorrect rendering of symbols (e.g., of quote(pi) and
expression(10^degree)) have been seen on Linux systems which have the
Wine symbol font installed – fontconfig then prefers this and
misinterprets its encoding. Adding the following lines to
‘~/.fonts.conf’ or ‘/etc/fonts/local.conf’ may circumvent this problem
by preferring the URW Type 1 symbol font.
<fontconfig>
<match target="pattern">
<test name="family"><string>Symbol</string></test>
<edit name="family" mode="prepend" binding="same">
<string>Standard Symbols L</string>
</edit>
</match>
</fontconfig>
Adding these lines to /etc/fonts/local.conf solved the problem for me.

I ran into a similar problem and after reading here and some other related issues I found a solution. I'm working with Rstudio, so I guess that if you are doing R without it you you will easily find your work around (hopefully).
My solution was to Tools -> Global Options
and here I changed my backend to Cairo.
This is how it looks the change:

As a workaround I am creating the axis labels manually. Still looking for a better solution and explanation of the undesired behaviour.
xlabs = seq(-84,-76, 2)
ylabs = seq(34, 36.5, 0.5)
ggplot() +
geom_sf(data = nc) +
scale_x_continuous(breaks = xlabs, labels = paste0(xlabs,'°W')) +
scale_y_continuous(breaks = ylabs, labels = paste0(ylabs,'°N')) +
theme(axis.text = element_text(size=16))

Related

R gridSVG package - MultiPanel gapminder - Simon Potter's code getting an error during execution

I am trying to run the code (that can be downloaded here https://sjp.co.nz/projects/gridsvg/demos/gapminder-multi/), which should create an animation of the gapminder data using the R package gridSVG.
I downloaded the files
In the 3 R files, I inserted a line in which I set the working directory to the folder that contains the above files setwd("my working directory")
I executed the gapminder.R file and I get the following 2 errors:
...
I tried to clear how it should work, but without success.
I haven't advanced skills in R and, by my opinion, R Documentation of grid and gridSVG packages is poor.
People need more examples, I think.
Look, on the page by your link you can find an e-mail of the author, who made this visual. Maybe, you write a letter to him?
Maybe, it worked in the previous version of this package? Or we have curve hands, I don't know.
But look:
grid.set(gPath, newGrob, strict = FALSE, grep = FALSE,
redraw = TRUE)
We should make a certain newGrob(right syntax is...?) and pass to animateGrob?
Also stumbled at the problem that gridSVG has not been really animating.
It seems gridSVG has not been updated to the ggplot change that must have happened in the meantime related to the grobbing:
Currently, ggplot is lazy-evaluating and grid.ls() and all other grid functions will print only top-level layout grob versus the grob tree gridSVG expects.
In order to fix it in the gapminder example one has to add grid.force() every time grobs are to be parsed:
e.g.,
g = ggplot(data=all) +
geom_point(aes(x=X1950.x, y=X1950.y, size=radius,
colour=continent),
shape=16, alpha=.5) +
scale_x_continuous(limits=c(1, 9),
name="Fertility\n(# children per woman)") +
scale_y_continuous(limits=c(10, 90),
name="Life Expectancy (at birth)") +
scale_colour_manual(values=continentCols) +
theme(legend.position="none") +
scale_size(range=c(1, 20))
# add grid.force(), otherwise grid.ls() and all other grid functions
# will see only top-level 'layout', there will be no tree to traverse.
grid.force()
# grid.ls()
# Try to animate
grid.set("geom_point", grep=TRUE,
animateGrob(grid.get("geom_point", grep=TRUE),
duration=20,
x=t(ggplotScaleX(as.matrix(all[xCols]),
1, 9)),
y=t(ggplotScaleY(as.matrix(all[yCols]),
10, 90))))
...
Also add the same change in the ggplotScale.R
calcGGplotScale <- function() {
# Produce a ggplot with two points at
print(ggplot(data.frame(x=0:1, y=0:1)) +
geom_point(aes(x=x, y=y)))
# Get the points grob
grid.force() # Add this to actually evaluate the grob-tree
# so the subsequent call makes sense.
grob <- grid.get("geom_point", grep=TRUE)
# Determine extent of scaled region
list(xrange=as.numeric(grob$x),
yrange=as.numeric(grob$y))
}

text in ggplot2 plots became rectangles with code [duplicate]

I have got the following problem: When I plot anything with ggplot2 like this
# Libraries
library(ggplot2)
# create data
xValue <- 1:10
yValue <- cumsum(rnorm(10))
data <- data.frame(xValue,yValue)
# Plot
ggplot(data, aes(x=xValue, y=yValue)) +
geom_line()
The resulting graph looks like this where the text is shown in weir unicode blocks:
ggplot2 graph with text issue
These unicode blocks look like boxes with four numbers starting with two 0s like:
# Example block
----
|00|
|2C|
----
I already tried to update and reinstall the tidyverse package, I reopened R-Studio and only called the library ggplot2 in order to have no conflicting packages open, I could not find any similar issue on the internet whatsoever. I hope you can help me out and please do not hesitate if you need further information from me.
R version: 3.6.1 (2019-07-05)
platform: linux mint x86_64
conda environment
EDIT: For anybody who is interested in solving this issue permanently look here. I had to upgrade to R Version 4.0.3 in order to make ggplot work properly again.
This looks a lot like a font issue. Maybe the default ggplot font is not installed or damaged? Try querying installed fonts (for Linux):
system("fc-list")
Output should be a list of entries like this:
/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf: DejaVu Serif:style=Book
Then you can set the font as a default for your ggplot theme (name of the ttf file is the correct way to name it as far as I can tell):
theme_set(theme_gray(base_family = "DejaVuSerif"))
If this returns the same result, try another one.
try to solve the problem by changing the text size and the color and theme of you're text? maybe that will work... sth like this:
ggplot(data, aes(x=xValue, y=yValue)) +
geom_line() + theme(text = element_text(size=20))

How to preserve colors saving from ggplot?

This may not be the right place to ask this question, but I'm having trouble saving my colors from ggplot. I made this plot (pic below), and used ggsave() to save it as a .png file, and I loved the way it looked. However, when I take that .png file and upload it anywhere (specifically, in this case, to twitter and UpWork), the colors distort. The blue and orange get much darker, and I like the plot much less. Why is this happening? Is it the way I'm saving? Is it a function of file compression on those websites?
Can anyone recommend a better way to save that will not influence the aesthetics of my plots?
Attached here are screenshots of what you can see on the file on my computer (first pic), and a screenshot of the uploaded version of that same exact file (second pic. Darker). Hopefully they both upload as they look to my computer here...
Here is an example of the code/colors I am using:
require(ggplot2)
plot <- ggplot(data=data.frame(x=c(1:3),y=c(1:3)),
aes(x=x,y=y))+
geom_point(col="#E56800", size=3)+
theme_classic()+
theme(panel.background = element_blank(),
plot.background = element_rect(fill = "#354154"),
text= element_text(color="#FCFFF9"),
axis.text = element_text(color="#FCFFF9"))
ggsave(plot, filename = "plot.png",
width = 5, height = 7,
dpi=300)
EDIT: By the way, I'm using RStudio on a Macbook Pro, in case that's relevant. I always get confused by the graphical device options, so I'm guessing they have something to do with this.
You can try to install the CRAN Cairo package, and add a type argument in ggsave like this:
ggsave(plot, filename = "plot.png",
width = 5, height = 7,
dpi=300,
type = "cairo-png") # add this argument
Cairo allows to export anti-aliased images (this is the default on Mac but not on PC), maybe this could help.

Embedded pdf-font in R-plot is not recognized by InDesign although available

Using ggplot2, extrafont and R's pdf device I have built plots in the cmyk colormodel that incorporate certain non-Windows fonts. The pdf-output looks fine and shows that the font has been embedded correctly, for instance "Arial-BoldMT".
Unfortunately, when trying to import the pdf into Adobe InDesign, I get the error message that the font "Arial-BoldMT" is not currently available, which also happens to the non-Windows fonts I mentioned above.
I suppose there might be a problem with the name of the embedded font that cannot be recognized by InDesign, since the font is very well available as "Arial" including all the variations such as "bold".
Any suggestions how to get those fonts working in InDesign by either adjusting the R script or using InDesign?
Thank you!
Here is a sample plot, similar to the plots I need to produce, just leaving out the unnecessary code lines:
library(ggplot2)
library(extrafont)
# define font
font <- "Arial"
# sample data
x <- data.frame(c("Personnel Costs", "Non-Personnel Costs", "Investments"),
c(33, 22, 45))
colnames(x) <- c("costs", "percent")
# plot
plot <- ggplot(x, aes("", y = percent, fill = factor(costs), width = 1.2))+
geom_bar(width = 4, stat="identity")+
# add the text (no font specification here)
geom_text(aes(label=costs),fontface = "bold")+
# no legend
theme(legend.position = "none") +
# pie-chart
coord_polar("y", start = 0.42, direction = 1)
# save plot
pdf("plot.pdf", family=font, colormodel="cmyk")
plot
dev.off()
PS: Using ggsave and embedFonts() with Ghostscript produced the same results.
Note: Using "Calibri" with the pdf device or ggsave and embed_fonts() does not work at all.
It seems if the font was not properly embedded into the pdf.
By running embed_fonts() after saving the plot, the according font got embedded and now works in InDesign.
I just needed:
library(extrafont)
embed_fonts(file="plot.pdf", outfile="plot.pdf")

Saving ggplot graph to PDF with fonts embedded in r

I've been following advice I've found online for saving a ggplot graph to PDF but I can't quite get it to work. I'm using the extrafont package to produce charts with text in Calibri, but my charts are printing out with no text. I don't know what I'm missing. I can't find any mistakes in my process. Hopefully, someone else can help.
Here's the code and process I used:
library(extrafont)
font_import(pattern="[C/c]alibri")
loadfonts(device="win")
I installed GhostScript at this time. Then ran the following to set the GhostScript location.
Sys.setenv(R_GSCMD = "C:\\Program Files\\gs\\gs9.21\\bin\\gswin64c.exe")
I then produced a chart using ggplot called "chart". The chart looked perfect in RStudio, but not in PDF.
ggsave("chart.pdf", plot = chart, width = 6, height = 4)
Here I get warnings showing stuff like this:
In grid.Call(C_textBounds, as.graphicsAnnot(x$label), ... : font family 'Calibri' not found in PostScript font database
Apparently, these warnings are supposed to happen? Then I run...
embed_fonts("chart.pdf", outfile="chart_embed.pdf")
Unfortunately, after all this, the final "embed" chart looks no different than the original chart produced, neither of which have any text.
In case it helps, here's the code to produce the chart:
a <- ggplot(data=stats, aes(x=Date))
Chart <- a + geom_point(aes(y=NevadaTotalNonfarmAllEmployees)) +
xlab("Date") +
ylab("Nonfarm Jobs") +
ggtitle("Nevada Total Jobs") +
theme(axis.title.x = element_text(size=15, family = "Calibri"),
axis.title.y = element_text(size=15, family = "Calibri"),
axis.text.x = element_text(size=10, family = "Calibri"),
axis.text.y = element_text(size=10, family = "Calibri"),
plot.title = element_text(hjust=0.5, size=20, family = "Calibri"))
I've been pulling my hair out trying to figure this out. Or maybe it's not the code but something else? Either way, thanks for any assistance.
There are a couple issues at play here: (1) loading fonts into R and (2) using a PDF-writing library that works correctly with custom embedded fonts.
First, as others have mentioned, on Windows you generally need to run extrafont::font_import() to register many of your system fonts with R, but it can take a while and can miss TTF and other types of fonts. One way around this is to load fonts into R on the fly, without loading the full database, using windowsFonts(name_of_font_inside_r = windowsFont("Name of actual font")), like so:
windowsFonts(Calibri = windowsFont("Calibri"))
This makes just that one font accessible in R. You can check with windowsFonts(). You have to run this line each time the script is run—the font loading doesn't persist across sessions. Once the font has been loaded, you can use it normally:
library(tidyverse)
df <- data_frame(x = 1:10, y = 2:11)
p <- ggplot(df, aes(x = x, y = y)) +
geom_point() +
labs(title = "Yay Calibri") +
theme_light(base_family = "Calibri")
p
Second, R's built-in PDF-writing device on both Windows and macOS doesn't handle font embedding very well. However, R now includes the Cairo graphics library, which can embed fonts just fine. You can specify the Cairo device in ggsave() to use it, which is easier than dealing with GhostScript:
ggsave(p, filename = "whatever.pdf", device = cairo_pdf,
width = 4, height = 3, units = "in")
I’ve found it safer to explicitly register fonts using pdfFonts (and/or postscriptFonts).
The documentation contains an example but also take a look at my fonts module. With this, registering a new font is as easy as writing
fonts$register_font('Calibri')
Internally, this creates a font specification using Type1Font, ensures that names are set correctly, and invokes pdfFonts.
It also ensures that the complete set of font metrics to exist (which is done using extrafont::ttf_import).
This way is considerably faster than generating font metrics for all fonts using font_import, and it gives you more control.
I think you missed the initialization step font_import(). Be forewarned, executing this command can take a bit longer time.
First, you can see what fonts you have available with the command windowsFonts(). The current fonts in my graphing device are;
$serif
[1] "TT Times New Roman"
$sans
[1] "TT Arial"
$mono
[1] "TT Courier New"
Thereafter, you can import the extrafont library and the loadfonts(device = "win"). I also recommend to execute these commands in the R console and not in RStudio. I suggest this because when you are importing the fonts using font_import() in RStudio, it may not show the y/n prompt.
Below I provide a minimum reproducible example;
library(ggplot2)
library(extrafont)
font_import()
# tell where ghostscript is located. This is required for saving the font in pdf
Sys.setenv(R_GSCMD = "C:\\Program Files\\gs\\gs9.21\\bin\\gswin64c.exe") # I have installed 64-bit version of GhostScript. This is why I've used gswin64c.exe. If you have installed 32-bit version of GhostScript, use gswin32c.exe. Failure to specify the correct installed GhostScript will yield error message, "GhostScript not found"
# create a plot object
p <- ggplot(mtcars, aes(x=wt, y=mpg)) +
geom_point()+
ggtitle("Fuel Efficiency of 32 Cars")+
xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
theme_bw()+
theme(text=element_text(family="ArialMT", size=14))
# show the plot
print(p)
# save the plot as pdf
ggsave("figures//ggplot_arialmt.pdf", p, width=20, height=20,
device = "pdf", units = "cm")
Note
Its only the ArialMT font that seems to work with ggsave(). See this SO post. Using any other font for saving to pdf, renders the figure with characters on top of another. This is also an open issue for ggsave and has not been answered since 2013.

Resources