Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

Formatting axis breaks, labels and legend when using secondary y axis ggplot2

$
0
0

I have added a secondary y axis to my plot (using ggplot2) and managed to get the scale on this axis OK. However, the scale on my primary y axis has now reverted back to the default rather than what I set it as.

I would also like to format the title on the secondary axis to be the same distance away from the axis as my other two, and not right next to the axis labels.

Finally, I would like a key just to say what the bars and line show.

Here is my data:

Month   Average Methane Flux    Standard Error CH4 flux Average Air temperature
Aug -967.19 1725.28 19.58
Sep 1428.95 718.88  19.17
Oct 1275.80 2968.65 12.70
Nov         
Dec         
Jan         
Feb         
Mar         
Apr         
May         
Jun         
Jul         

Code:

Month1 <- factor(Month, levels=unique(as.character(Month)))

p <- ggplot(data = Elstow.monthly.fluxes, 
            aes(x = Month1, y = Average.Methane.Flux)) + 
  geom_bar(stat = "identity", colour = "black") + 
  geom_errorbar(aes(ymin = Average.Methane.Flux - Standard.Error.CH4.flux, 
                    ymax = Average.Methane.Flux + Standard.Error.CH4.flux, 
                    width = 0.4)) +
  geom_line(data = Elstow.monthly.fluxes, 
            aes(Month1, Average.Air.temperature*100, group = 1), 
            colour = "Red", size = 1) + 
  xlab(expression("Month")) + 
  ylab(expression(Average~CH[4]~Flux~(µg~CH[4]~m^{-2}~d^{-1}))) + 
  scale_y_continuous(breaks = seq(-3000,4500,500)) + 
  scale_y_continuous(sec.axis = sec_axis(~./100, 
                                         name = "Average Air Temperature (°C)",  
                                         breaks = seq(-25,45,5))) + 
  theme(axis.text.x = element_text(colour = "black")) + 
  theme(axis.text.y = element_text(colour = "black")) + 
  theme(panel.background = element_rect("white", "black")) + 
  theme(panel.border = element_rect(colour = "black", fill=NA, size=0.5)) +
  theme(axis.text = element_text(size = 12))+ 
  theme(axis.title = element_text(size = 14))+ 
  theme(axis.title.y = element_text(margin = margin(t = 0, r = 10, b = 0, l = 0))) + 
  theme(axis.title.x = element_text(margin = margin(t = 10, r = 0, b = 0, l = 0)))

print(p)

Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>