Using ggplot2 and special characters

陌路散爱 提交于 2020-01-04 06:03:58

问题


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


来源:https://stackoverflow.com/questions/33402920/using-ggplot2-and-special-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!