Using ggplot2 and special characters

2019-08-11 05:38发布

问题:

I am reading in data from a web site, with text identifying each row. I simply copied and pasted the data into Excel, and the file is then read by R. One of these rows contains the name of a German city, "Würzburg", which includes a lower case u with an umlaut. I have no problem seeing the special character on the web or on Excel. The problem is, when this word is passed to ggplot2, it is displayed in the plot as "WÃzburg", with tilde over the capital A. RStudio shows both forms depending on the area in which it is displayed. I would assume that ggplot2 uses a different language for interpreting the special characters.

Is there a way to tell ggplot how to read, interpret and display the special characters? I do not want to write specialized code just for this city, but to solve the problem in general. I am likely to encounter other characters as the data expands over time.

回答1:

Read the file in as follows

library('data.table')
fread('path_to_file', ..., encoding = 'UTF-8')


回答2:

I encountered a similar error with ggplot2, when I used a hardcoded data.frame (i.e., I would write Großbritannien (Great Britain) and it would get encoded to some gibberish).

My solution was to include

Sys.setlocale("LC_ALL", "German")
options(encoding = "UTF-8")

in the beginning of the script.



回答3:

My solution to this problem is switching to cairo for pdf plotting. All special characters are shown properly by the ggplot2. It is enough to put this line of code among the knitr settings:

knitr::opts_chunk$set(dev='cairo_pdf')