Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate and customize secondary y axis

This should be simple but I am getting some errors. I want to duplicate and then customize the labels of the secondary y axis.

First, this simple code should yield the following figure:

  ggplot(data = mpg, aes(x = displ, y = hwy)) + 
      geom_point() +
      scale_x_continuous(sec.axis = dup_axis()) +
      scale_y_continuous(sec.axis = dup_axis())

enter image description here

But I don't know why I get the following error (it works without the scale_ arguments and I have ggplot2 version 2.2.1):

Error in .Call(rhs, f) : first argument must be a string (of length 1) or native symbol reference

Second, once the y axis is duplicated in right side, I would like to change the tick labels (20, 30, 40) for, let's say, ("a", "b", "c").

How can I fix that error and customize the tick labels of the secondary y axis?

like image 632
jlp Avatar asked May 27 '17 23:05

jlp


1 Answers

The first part of the code works well for me with the same version of ggplot2(2.2.1). In relation to your second question, using sec_axis() does the job. The first argument is the transformation formula trans, since you want to have the same scale but change just the labels then use ~ . * 1 e.g.:

ggplot(data = mpg, aes(x = displ, y = hwy)) + 
  geom_point() +
  scale_x_continuous(sec.axis = dup_axis()) +
  scale_y_continuous(sec.axis = sec_axis(~ . * 1, breaks = c(20,30,40), labels = c("a","b","c")))

enter image description here

Note: Be aware that the "transformation for secondary axes must be a formula".

like image 84
Edgar Santos Avatar answered Oct 06 '22 04:10

Edgar Santos