R ggplot2 gave accent in legend

Viewed 1113

I created a function to plot some data per city in a line graph. I want the user to be able to change the label of each city in the legend.

A simplified example:

example_plot <- function(plot_labs = c("Anvers", "Liège")){

graphics.off()

input <- data.table(x_axis = c(1, 2, 3, 4, 5, 1, 2, 3, 4, 5), 
                y_axis = c(5, 6, 4, 2, 8, 9, 3, 1, 7, 5),
                City = c("Anvers", "Anvers", "Anvers", "Anvers", "Anvers", 
                         "Liege", "Liege", "Liege", "Liege", "Liege"))

ggplot(data = input, aes(x = x_axis, y = y_axis, group = City, lty = City)) + 
geom_line() + scale_linetype_manual(labels = plot_labs, breaks = c("Anvers", 
"Liege"), values = 1:2)
}

My problem:

When I save the function as "example_plot.R" and then call it in the command prompt with no argument, the accent in "Liège" does not display correctly:

example_plot()

enter image description here

If I call the function with the plot_labs argument, it displays correctly:

example_plot(plot_labs = c("Anvers", "Liège"))

enter image description here

What I find even stranger is that if I copy-paste the function's code in the command prompt (instead of 'source(example_plot.R")'), then everything works fine.

Any idea why it behaves differently when the function is saved?

1 Answers

You're probably saving your source file in an encoding such as UTF-8 and then reopen or source it assuming it's in Latin-1.

If you're using RStudio, check the menu points File/Save with encoding, and File/reopen with encoding, and ensure the character encodings match.

Related