Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: How to format the sec.axis properly in R

Tags:

r

scale

ggplot2

I am trying to plot 3 lines using geom_line() in my ggplot graph. One of the variables has a different scale so I am trying to use the sec.axis in order to show it as well.

library(ggplot2)
library(reshape2)

tab <- data.frame(year = seq(1979,2010), freq = runif(32, 212,283), max = 
runif(32, 962.1, 993.4), med = runif(32, 972.1, 989.3), min = runif(32, 
955.7, 978.3))

summary(tab) # the column freq (frequency) has a different scale comparing with the other ones

Some code I've tried.

tab <- melt(tab, id = c("year")) # melt the data

ggplot(tab, aes(x = year, y = value)) + 
theme_bw() + 
scale_colour_manual(values =c('red','blue', 'green')) + 
geom_line() + 
scale_y_continuous(limits = c(900,1000), sec.axis = sec_axis(~. *0.3)) # I am using limits in order to control the extent for the other variabiles besides 'freq'.

This shows the second y_axis but the variable 'freq' is missing. So far, I could not find an example showing how to plot multiple lines using a sec.scale as well for one variable. Also, I am not sure if I need to transform the 'freq' variable first or only to control the sec.axis for it so if anyone can explain me, I will be grateful.

Thanks!

like image 226
Andrei Niță Avatar asked Mar 04 '23 17:03

Andrei Niță


1 Answers

You can also use geom_pointrange, without melting the data. I changed the data little bit to make the graph nicer, but you can adapt it later for your data.

tab <- data.frame(year = seq(1979,2010), freq = runif(32, 280,300), max = 
                    runif(32, 975.1, 993.4), med = runif(32, 972.1, 975.3), 
                  min = runif(32,955.7, 971.3))   

ggplot(data = tab, mapping = aes(x = year)) +
  geom_pointrange(mapping = aes(y=med,ymin = min, ymax = max),size=0.5,color='blue',fatten = 1)+theme_bw()+
  geom_point(aes(x=year,y=freq/0.3), inherit.aes = FALSE,color='red')+
  scale_y_continuous( name = 'range and median', sec.axis = sec_axis(~. *0.3,name = "frequency"))+
  theme(axis.text.y  = element_text(color = 'blue'),
    axis.title.y = element_text(color='blue'),
    axis.text.y.right =  element_text(color = 'red'),
    axis.title.y.right = element_text(color='red'))

enter image description here

like image 193
Senzeybek Avatar answered Mar 07 '23 21:03

Senzeybek