1
votes

I have plotted a graph with two y-axes. However, the titles of the axes are a little too close to them for my taste. I've managed to distance the primary axis title but can't figure out how to do the same for the secondary axis. Here is the code I've used:

ggplot(data1, aes(x=year))+
geom_line(aes(y= data1$`export share`, colour= "export share"), size = 2)+
  geom_line(aes(y=data1$pm25/coeff, colour= "pm25"), size = 2)+
  scale_x_continuous(breaks = scales::pretty_breaks(n = 17), name = "Year")+
  scale_y_continuous(name="Export Share of GDP", labels = scales::percent, sec.axis=sec_axis(trans = ~.*coeff, name = "PM2.5"))+
  theme(axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)), axis.text.x = element_text(vjust = 5) ,legend.title = element_blank(), legend.box.margin = margin(0,0,0,10), text = element_text(size = 30)) +
  scale_colour_discrete("",
                        breaks=c("export share", "pm25"),
                        labels=c("Export Share of GDP", "PM2.5")) +
  geom_vline(xintercept=2006) +
   geom_vline(xintercept = 2000)

And here's a picture of the graph

1
Yes, unfortunately it didn't seem to change anything except create a margin to the left of the primary axis.oliver1902
The best victories are the battles that we never fought. I would recommend avoiding the secondary y-axis entirely. Two graphics one below the other would be more appropriate. A secondary y-axis might yield visual confusion. I would suggest this reading to make my case.DJJ
I would avoid using dual y axes. In most cases it is not a good idea. I would pivot your data long, index the measurements to some starting number (the value at year 2000), and then plot them on the same axis.Conor

1 Answers

2
votes

You can increase the margin on the right by increasing the second argument of plot.margin

+ theme(plot.margin=unit(c(1,3,1,1), "cm"))

And then increase the vjust argument of axis.title.y.right:

+ theme(axis.title.y.right = element_text(vjust=2 or 3 or 4))

Larger numbers for vjust go further away from the axis. Of course you combine the above two "theme" commands into one.