Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double x-axes at bottom using ggplot in R

Tags:

r

ggplot2

I am trying to create a RMT plot in which I want a double x-axes, yet both displayed at the bottom. I have found some examples using other R packages (like for example this lattice example but I was wondering if anyone knows a way to do it using ggplot2?

Creating fake data frame similar to mine, each data point consists of different percentages of a,b,c (note a+b+c=100% for each point). At the same time there are three types of vegetation points I want coloured differently:

a <- c(10,30,40,20,30,50,20,10,30,20,60,20)
b <- c(20,30,10,40,60,20,30,60,30,10,20,70)
c <- c(70,40,50,40,10,30,50,30,40,70,20,10)
d <- rep(c("tree", "grass", "herbs"),4)

df_trio <- data.frame(a,b,c,d)

Creating plot with two x-axes (one top and one bottom) with the percentages going from 0-100% on the first x-axis and 100-0% on the second:

plot_trio <- ggplot(df_trio, aes(a,b)) +
  geom_point(aes(colour = factor(d)))+
  theme_classic()+
  coord_cartesian(xlim = c(0,100), ylim = c(0,100), expand = FALSE)+
  scale_x_continuous(breaks = c(0,10,20,30,40,50,60,70,80,90,100),"%a", 
                 sec.axis = sec_axis((~(.-100)*-1), name = "%c", 
                 breaks = c(100,90,80,70,60,50,40,30,20,10,0)))+
  scale_y_continuous(breaks = c(0,10,20,30,40,50,60,70,80,90,100))+
  ylab("%b")+
  geom_abline(slope = -1, intercept = 100)+
  annotate("text", label="0% of c",x=55,y=52, size=3)

plot_trio

The slope line shows where factor c is 0% (it is 100% if factor a and b are 0, so in the origin).

I tried to use

 scale_x_continuous(breaks=c(0,10,20,30,40,50,60,70,80,90,100),"%a", 
                 position="top", sec.axis = sec_axis((~(.-100)*-1), name = 
                 "%c", breaks=c(100,90,80,70,60,50,40,30,20,10,0)))

to force them both to the top but then they just switch. Does anyone have a tip on in which direction I should go to do this, or should I just give up on ggplot and use lattice instead?

like image 446
sv1989 Avatar asked Sep 12 '25 10:09

sv1989


1 Answers

This looks like a good use case for ggtern:

df_trio <- data.frame(a = c(10,30,40,20,30,50,20,10,30,20,60,20),
                      b = c(20,30,10,40,60,20,30,60,30,10,20,70),
                      c = c(70,40,50,40,10,30,50,30,40,70,20,10),
                      d = rep(c("tree", "grass", "herbs"),4))
require(ggtern)
ggtern(df_trio, aes(a, b, c, colour = d)) + 
  geom_point(size = 4) + 
  theme_light() + theme_showarrows() + 
  labs(xarrow = "% a", yarrow = "% b", zarrow = "% c")

enter image description here

like image 71
Brian Avatar answered Sep 15 '25 02:09

Brian