user13317
user13317

Reputation: 505

Double inequality in ggplot2 facet label

How does one put a double inequality into a facet label in ggplot2?

#Fake some data
  x = seq(1,100,length.out=100)

#Relationship with beta for model y = a*x^b
  alpha = 0.5
  beta1 = -0.1
  beta2 = 0.01
  beta3 = 3

#Fitted values
  y1 = alpha*x^beta1
  y2 = alpha*x^beta2
  y3 = alpha*x^beta3

#Create a data frame
  df = data.frame(x=rep(x,3),y=c(y1,y2,y3),type=rep(c('beta < 0','0 < beta < 1','beta > 1'),each=100))

#Ggplot it up
  ggplot(data=df,aes(x=x,y=y)) + geom_line() + facet_wrap(~type,labeller=label_parsed,scales='free_y')

However, this fails and I get the following error

Error in parse(text = as.character(values)) : 
  <text>:1:9: unexpected input
1: 0 < beta

How to get around this?

Upvotes: 2

Views: 434

Answers (1)

aosmith
aosmith

Reputation: 36084

You can split the label with double quotes around the first part with an asterisk much like in this answer.

The label in question then looks like:

'"0 < "*beta < 1'

To make sure all greater than/less than signs look the same, use the quotes and asterisks for all non-Greek symbols when making the labels.

If you want the result in a specific order, you will likely need to order the factor type.

df = data.frame(x=rep(x,3),y=c(y1,y2,y3), 
             type=rep(c('beta*" < 0"','"0 < "*beta*" < 1"','beta*" > 1"'), each=100))

df$type = factor(df$type, levels = unique(df$type))

ggplot(data = df, aes(x = x,y = y)) + geom_line() + 
    facet_wrap(~type, labeller = label_parsed, scales = 'free_y')

enter image description here

Upvotes: 4

Related Questions