Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ggplot2 and special characters

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.

like image 712
Paul M Avatar asked Feb 21 '26 09:02

Paul M


2 Answers

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.

like image 141
David Avatar answered Feb 24 '26 03:02

David


Read the file in as follows

library('data.table')
fread('path_to_file', ..., encoding = 'UTF-8')
like image 40
gented Avatar answered Feb 24 '26 03:02

gented



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!