Reputation: 23
I'd like to plot the sample dataset shown below like so: Y axis - Var2 (linear scale); X_bottom_axis - Var1 (linear scale); X_top_axis - Var3 (log scale)
The problem is that all my top X-axis is cramming together all the ticks and doesn't function as log scale. The picture exemplifies the format I want to achieve for my plot. Any ideas?
Below code shows a sample dataset and my unsuccessful attempt to plot it
d1 <- data.frame(var1=c(1,2,3,4,5),var2=c(100,110,99,94,100),var3=c(1e-6,12e-6,27e-6,1e-5,1e-3))
ggplot(d1,aes(y=var2))+geom_point(aes(x=var1),col="blue")+geom_point(aes(x=var3),col="red")+scale_x_continuous(sec.axis = sec_axis(~., breaks = c(1e-6,1e-5,1e-4,1e-3,1e-2,1e-1,0)))
Upvotes: 0
Views: 94
Reputation: 174348
Adding a secondary axis doesn't change where the red dots are plotted. You need to apply a transformation to the data so that they are approximately on the same scale as the blue dots. For example. taking log10
of var3
and adding 6 will change the red dots to be between the values of 1 and 3 so they are clearly visible on the plot. All the secondary axis does is to provide an annotation showing how these red dots should be interpreted. To do this, you need to pass a function that inverts this transformation (i.e. ~10^(.x - 6)
ggplot(d1, aes(y = var2)) +
geom_point(aes(x = var1), col = "blue") +
geom_point(aes(x = log10(var3) + 6), col = "red")+
scale_x_continuous(sec.axis = sec_axis(~10^(.x - 6), breaks = 10^(-6:0))
Upvotes: 2