为ggplot复制离散的x轴

时间:2018-02-24 16:05:53

标签: r ggplot2

嗨,这与另一篇文章相似,但我想在这里做的是顶部和底部的重复x轴,而不仅仅是将它移到顶部。我尝试使用scale_x_discrete(sec.axis = dup_axis()),但这不起作用。以下是我的工作示例

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())

情节目前看起来像这样,但我希望x显示顶部和底部。 enter image description here

1 个答案:

答案 0 :(得分:4)

scale_x_discrete函数没有第二个轴参数,但是scale_x_continuous。因此,将type变量编辑为数字变量然后更改标签将起作用:

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