0

I have a problem when draw plot with double x-axis (one of the x-axis is an axis transformation). My expected result is even though they have same scale range, but one of the axes has 8mm left deviation (The second x-axis have left align with the main x-axis)

Expect output (like this):

enter image description here

But now, it is same range, same align.

enter image description here

This is my code:

library(ggplot2)
library(cowplot)

data <- data.frame(temp_c=runif(100, min=-5, max=30), outcome=runif(100))

plot <- ggplot(data) + 
  geom_point(aes(x=temp_c, y=outcome)) + 
  theme_classic() + 
  labs(x='Temperature (Celsius)')

x2plot <- ggplot(data) + 
  geom_point(aes(x=temp_c, y=outcome)) + 
  theme_classic() + 
  scale_x_continuous(label=function(x) x) + 
  labs(x='Temperature (Fahrenehit)')

x <- get_x_axis(x2plot)
xl <- get_plot_component(x2plot, "xlab-b")

plot_grid(plot, ggdraw(x), ggdraw(xl), align='v', axis='rl', ncol=1, 
          rel_heights=c(0.8, 0.05, 0.05))

Please help me. Thank you so much.

Linh
  • 147
  • 7
  • Does this answer your question? [Order Bars in ggplot2 bar graph](https://stackoverflow.com/questions/5208679/order-bars-in-ggplot2-bar-graph) – Patrick Sep 08 '21 at 06:38
  • Thank you @Patrick, but that is the order, my question is the second X-axis left align with the main X-axis. – Linh Sep 08 '21 at 06:44

1 Answers1

1

You cannot do axis='lr', this will force both both plots to aligned left to right. Also this ggdraw(xl) will not work. If it is indeed 0.8mm, you can create the 2nd plot with 0.8mm offset:

g = x2plot+theme(plot.margin=margin(0,0,0,0.8,unit="mm"))
x = ggdraw(get_x_axis(x2plot)) 

Then call plot_grid :

plot_grid(plot, ggdraw(x), align='v', axis='l', ncol=1, 
          rel_heights=c(0.8, 0.05))+
draw_label("Temperature (Fahrenehit)",
x=0.5, y=  0, vjust=-0.1, angle= 0,size=11)

enter image description here

StupidWolf
  • 45,075
  • 17
  • 40
  • 72
  • Thank @StupidWolf, I'm not clear, I have adjusted margin the second plot (like you), but the skewed between the first scale plot and the second one are not different, even though you see have a little bit change – Linh Sep 08 '21 at 07:29
  • I think when you adjust the second margin, you only scale this plot, but if you call the same grid with the first plot, you will break the margin set up before? – Linh Sep 08 '21 at 07:35