Steen Harsted
Steen Harsted

Reputation: 1932

Using Unicode character (plus minus sign) inside ggplot2

I am trying to build a plot that includes a unicode character (The plus-minus sign U+00B1)

Here is some fake data:

library(tidyverse)
set.seed(1)
df <- crossing(
  Rated_Movement = c("Running", "Jumping"),
  Rater = c("John Snow", "Batman", "Hulk")) %>% 
  mutate(
    Error = runif(n = 6, min = 0, max=2))

Here is my code for the plot so far:

ggplot(df, aes(x = Rated_Movement, y = Rater, fill = Error)) + 
  geom_tile(color = "black", size = 0.5, alpha = 0.8)+
  geom_text(aes(label = paste("+-", round(Error,2))))+
  scale_fill_gradientn(colours = terrain.colors(10))+
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())

Here is the plot:
Plot

Is there a way that I can change the +- to unicode character U+00B1

I tried using the backslash to escape: paste("\U+00B1", round(Error,2)) But I get the error: "Error: '\U' used without hex digits in character string starting ""\U""

Any help will be much appreciated. Best regards

Upvotes: 3

Views: 3160

Answers (1)

missuse
missuse

Reputation: 19756

here are two ways:

ggplot(df, aes(x = Rated_Movement, y = Rater, fill = Error)) + 
  geom_tile(color = "black", size = 0.5, alpha = 0.8)+
  geom_text(aes(label = paste("±", round(Error,2))))+
  scale_fill_gradientn(colours = terrain.colors(10))+
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())

ggplot(df, aes(x = Rated_Movement, y = Rater, fill = Error)) + 
  geom_tile(color = "black", size = 0.5, alpha = 0.8)+
  geom_text(aes(label = paste("\u00B1", round(Error,2)))) +
  scale_fill_gradientn(colours = terrain.colors(10))+
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())

enter image description here

Upvotes: 5

Related Questions