为ggplot复制离散的x轴

Ahd*_*dee 6 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())
Run Code Online (Sandbox Code Playgroud)

该图当前看起来像这样,但我希望x显示在顶部和底部。 在此处输入图片说明

Mic*_*per 7

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())
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明