Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicating discrete x-axis for ggplot [duplicate]

Tags:

r

ggplot2

Hi this is similar to another post however what I wanted to do here is duplicate x-axis for top and bottom and not just move it to the top. I tried using scale_x_discrete(sec.axis = dup_axis()) but that did not work. Below is my working example

d<- data.frame (pid=c("d","b","c"), type=c("rna","rna","rna"), value = c(1,2,3) )
d2 <- data.frame (pid=c("d","b","c"), type=c("dna","dna","dna"), value = c(10,20,30) )
df <- rbind (d,d2)

ggplot(df, aes(y=pid, x=type  ) ) + 
  geom_tile(aes(fill = value),colour = "white") + 
  scale_fill_gradient(low = "white",high = "steelblue") +
  scale_x_discrete(position = "top") 
  # this failed: scale_x_discrete(sec.axis = dup_axis())

The plot currently looks like this but I want x to show up top and bottom. enter image description here

like image 716
Ahdee Avatar asked Feb 24 '18 16:02

Ahdee


1 Answers

The scale_x_discrete function does not have a second axes argument, but scale_x_continuous does. So editing the type variable to a numeric variable and then changing the label would work:

d<- data.frame (pid=c("d","b","c"), type=1, value = c(1,2,3) )
d2 <- data.frame (pid=c("d","b","c"), type= 2, value = c(10,20,30) )
df <- rbind (d,d2)

ggplot(df, aes(y=pid, x=type)) + 
  geom_tile(aes(fill = value),colour = "white") + 
  scale_fill_gradient(low = "white",high = "steelblue") +
  scale_x_continuous(breaks = 1:2,
                      labels = c("rna", "dna"),
                      sec.axis = dup_axis())

enter image description here

like image 185
Michael Harper Avatar answered Sep 21 '22 13:09

Michael Harper