Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

less than equals in ggplot2 axis label

Tags:

r

ggplot2

I am trying to get the <= in the xaxis labels to show up correctly. I have seen previous posts with expression. In each of those examples, there was only 1 label which was done explicitly (manually). In my case, there are several labels with <=. I read the factor labels from a file.

faclab <- "value,label
1,<= 1
2,1 < ... <= 2
3,2< ... <= 3
4,>3"
labels.dt <- fread(faclab)

data <- data.table(value=sample(labels.dt[['value']],100,replace=TRUE))

ggplot(data, aes(factor(value))) + geom_bar(aes(y=(..count..)/sum(..count..))) +
   scale_x_discrete(breaks=labels.dt[['value']], labels=labels.dt[['label']])
like image 723
ironv Avatar asked Nov 26 '25 09:11

ironv


1 Answers

Replace "<=" with the appropriate unicode character "\u2264" ("≤"):

stringi::stri_replace_all_fixed(
  c("<= 1", ">= 2"), 
  c("<=", ">="), 
  c("\u2264", "\u2265"), 
  vectorize_all = F
)
# [1] "≤ 1" "≥ 2"

For example:

library(tidyverse)
library(data.table)
faclab <- "value,label
1,<= 1
2,1 < ... <= 2
3,2< ... <= 3
4,>3"
labels.dt <- fread(faclab)
data <- data.table(value=sample(labels.dt[['value']],100,replace=TRUE))
ggplot(data, aes(factor(value))) + geom_bar(aes(y=(..count..)/sum(..count..))) +
  scale_x_discrete(
    breaks=labels.dt[['value']], 
    labels=stringi::stri_replace_all_fixed(labels.dt[['label']], "<=", "\u2264")
  ) 

enter image description here

like image 103
lukeA Avatar answered Nov 27 '25 21:11

lukeA



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!