2

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.

Peter
  • 7,460
  • 2
  • 47
  • 68
Paul M
  • 677
  • 1
  • 8
  • 15
  • You probably need to consider unicode representation for your strings. [Here](http://stackoverflow.com/questions/29265172/print-unicode-character-string-in-r) is a related post. You might need [this](http://www.alanwood.net/unicode/latin_1_supplement.html) – Shawn Mehan Oct 28 '15 at 22:52

3 Answers3

5

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.

David
  • 9,216
  • 4
  • 45
  • 78
2

Read the file in as follows

library('data.table')
fread('path_to_file', ..., encoding = 'UTF-8')
gented
  • 1,620
  • 1
  • 16
  • 20
  • Thank you! I added the encoding for read.xlsx, and it worked fine. This may be widely available. – Paul M Oct 28 '15 at 23:13
0

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')