【问题标题】:GGPlot Flip This PlotGGPlot 翻转这个图
【发布时间】:2020-05-22 17:58:13
【问题描述】:
library(ggplot2)
library(reshape2)
HAVE = data.frame(VARS = c("cat", "dog", "fox", "rabbit"),
                  "a" = c(1,2,3,4),
                  "b" = c(2,3,1,4),
                  "c" = c(3,1,2,4))

HAVE1 = melt(HAVE, id.vars="VARS")

ggplot(HAVE1, aes(VARS, variable, fill= value)) + 
  geom_tile() +
  scale_fill_gradient(low="white", high="blue")

我希望生成从黄色(低值)到蓝色(高值)的颜色图。我希望顶部的列是“变量”,而 yticks 是 VARS,例如:请注意这只是一个示例!!


【问题讨论】:

    标签: r ggplot2 heatmap


    【解决方案1】:

    这里有一个带有coord_flip 的选项来切换轴和使用fct_rev 重新排序因子水平

    ggplot(HAVE1, aes(x = fct_rev(as_factor(VARS)), variable, fill= value)) + 
      geom_tile() +
      scale_fill_gradient(low="yellow", high="blue") +
      coord_flip()
    

    【讨论】:

      【解决方案2】:

      这是pivot_longer 和scale_x_discrete 的一种方法。请注意,tidyr 是 reshape2 的继承者,但由同一作者撰写。

      我们可以重新排序VARS 的因子水平,让它们按照您想要的顺序进行绘图。

      我们也可以用labs和element_blank去掉坐标轴标签。

      library(ggplot2)
      library(tidyr)
      library(dplyr)
      HAVE %>% 
        pivot_longer(-VARS,names_to = "variable", values_to = "value") %>%
      ggplot(aes(x = variable, y = factor(VARS, rev(levels(VARS))), fill= value)) + 
        geom_tile() +
        scale_fill_gradient(low="yellow", high="blue") +
        scale_x_discrete(position = "top") +
        labs(x = element_blank(), y = element_blank())
      

      如果您希望瓷砖是方形的,只需添加 coord_equal() 函数:

      ggplot(HAVE1,aes(x = variable, y = factor(VARS, rev(levels(VARS))), fill= value)) + 
        geom_tile() +
        scale_fill_gradient(low="yellow", high="blue") +
        scale_x_discrete(position = "top") +
        labs(x = element_blank(), y = element_blank()) + 
        coord_equal()
      

      【讨论】:

      • 非常感谢,是的,这很棒——我想知道矩形可以是更小的盒子/正方形吗?我尝试对此进行修改,但未能
      • 我认为添加coord_equal() 应该是您想要的。
      • 要反转图例,请添加+ guides(fill = guide_colorbar(reverse = TRUE))。图像的大小由 Rstudio 或在您对 png 或 pdf 的调用中控制,而不是 ggplot。
      • 如果是x轴标签,可以试试+ theme(axis.text.x = element_text(angle = 90))?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-20
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多