Double x-axes at the bottom using ggplot in R

I am trying to create an RMT slice where I want a double x axis, but both are displayed at the bottom. I found some examples using other R packages (like this lattice example , but I was wondering if anyone knows how to do this using ggplot2?

Creating a fake dataframe like mine, each data point is made up of different percentages of a, b, c (note a + b + c = 100% for each point). At the same time, there are three types of plant dots that I want to color in different ways:

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)

      

Create a graph with two x-axes (one top and one bottom) with percentages ranging from 0-100% on the first x-axis and 100-0% for a 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 c is 0% (it is 100% if a and b are 0, so at 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 hint as to which direction I should go to do this, or should I just give up ggplot and use the lattice instead?

+3


source to share


1 answer


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

+2


source







All Articles