4

I wonder if it is possible (I know it is) to keep the plot's axis labels in one side of the plot and the plot's axis title in the opposite side, specifically in a discrete geom_tile() plot as follows: change axis title to other position

Bernardo
  • 461
  • 7
  • 20

1 Answers1

5

You can use sec.axis = dup_axis() inside scale_x_*() to duplicate both axis then remove what you don't need inside theme().

ggplot(mtcars, aes(x=mpg, y=hp)) +
  geom_point() +
  labs(title="mpg vs hp") +
  scale_y_continuous(position = 'right', sec.axis = dup_axis()) + 
#remember to check this with the proper format
  scale_x_continuous(position = "top", sec.axis = dup_axis()) +
  theme(plot.title = element_text(hjust=0.5),
        axis.text.x.top = element_blank(), # remove ticks/text on labels
        axis.ticks.x.top = element_blank(),
        axis.text.y.right = element_blank(),
        axis.ticks.y.right = element_blank(),
        axis.title.x.bottom = element_blank(), # remove titles
        axis.title.y.left = element_blank())

enter image description here


Other example and with a theme_new() function:

theme_new <- function() {
  theme(plot.title = element_text(hjust=0.5),
        axis.text.x.top = element_blank(), # remove ticks/text on labels
        axis.ticks.x.top = element_blank(),
        axis.text.y.right = element_blank(),
        axis.ticks.y.right = element_blank(),
        axis.title.x.bottom = element_blank(), # remove titles
        axis.title.y.left = element_blank())
}

ggplot(df, aes(x, y)) +
  geom_tile(aes(fill = z), colour = "grey50") +
  labs(title="some title") +
  scale_y_continuous(position = 'right', sec.axis = dup_axis()) + 
  scale_x_continuous(position = "top", sec.axis = dup_axis()) +
  theme_new()

enter image description here

RLave
  • 8,144
  • 3
  • 21
  • 37
  • Awesome answer @RLave Thanks for your time and help! But they are discrete variables, not continuous. So I get the `Error: Discrete value supplied to continuous scale` error. And, on the other hand, using `scale_x_discrete` I get `unused argument (sec.axis = dup_axis())` – Bernardo Feb 22 '19 at 15:56
  • 1
    @Bernardo here a workaround with `discrete` https://stackoverflow.com/questions/45361904/duplicating-and-modifying-discrete-axis-in-ggplot2. – RLave Feb 23 '19 at 08:50
  • 1
    You need to force `as.numeric()` then you can play with `scale_*_continuos()`. – RLave Feb 23 '19 at 08:51