8

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

Ahdee
  • 4,679
  • 4
  • 34
  • 58
  • If you have found similar questions, can you provide links and also explain what didn't work with them? – Michael Harper Feb 24 '18 at 16:24
  • a similar post is here, https://stackoverflow.com/questions/26838005/putting-x-axis-at-top-of-ggplot2-chart however this was only to move the axis to the top and duplication is for continous – Ahdee Feb 24 '18 at 16:29
  • I just found a solution by converting to numeric and then relabeling but I'm wondering if there is another ggplot option. ```df$type <- as.numeric ( df$type ) 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 = c(1, 2), labels = c("Start", "n-1"), sec.axis = dup_axis() ) ``` – Ahdee Feb 24 '18 at 16:30
  • This should be added to the question, not the comments – Michael Harper Feb 24 '18 at 16:34

1 Answers1

11

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

Michael Harper
  • 14,721
  • 2
  • 60
  • 84