【问题标题】:R Color Map With Wide File带有宽文件的 R 彩色图
【发布时间】:2019-07-26 00:09:51
【问题描述】:
data=data.frame("team"=c("hawks","sharks","kongs","wolves"),
                "v1"=c(runif(4, -1, 1)),
                "v2"=c(runif(4, -1, 1)),
                "v3"=c(runif(4, -1, 1)),
                "v4"=c(runif(4, -1, 1)))

library(ggplot2)
p <- ggplot(data, aes(team,v1:v4)) + geom_tile(aes(fill = v1:v4[[]]), colour = "white") + scale_fill_gradient(low = "white", high = "steelblue")

base_size <- 9
p + theme_grey(base_size = base_size) + labs(x = "", y = "") + scale_x_discrete(expand = c(0, 0)) +
     scale_y_discrete(expand = c(0, 0))

我试图保持我的数据格式宽并创建显示的热图:

我的尝试失败了,因此我寻求社区的支持。我必须保持数据宽格式,因为我的真实数据以特殊方式排序。

【问题讨论】:

    标签: r colors dplyr heatmap heat


    【解决方案1】:

    要使用geom_tile,您必须将数据框设为长格式。 y 轴标签的排序不是基于数据框是长格式还是宽格式,而是由因子级别确定。我在下面提供了代码示例。

    顺便说一句,我还提供了其他代码示例来模仿您提供的示例图的样式。希望这些对您有所帮助。

    set.seed(1)
    data=data.frame("team"=c("hawks","sharks","kongs","wolves"),
                    "v1"=c(runif(4, -1, 1)),
                    "v2"=c(runif(4, -1, 1)),
                    "v3"=c(runif(4, -1, 1)),
                    "v4"=c(runif(4, -1, 1)))
    
    library(tidyverse)
    
    data2 <- data %>% 
      # Convert to long format
      gather(V, Value, -team) %>%
      # Set the factor level for the ordering of the team
      mutate(team = factor(team, levels = rev(c("hawks","sharks","kongs","wolves"))))
    
    ggplot(data2, aes(x = V, y = team, fill = Value)) +
      # Set the tile line to be white
      geom_tile(color = "white") +
      # Change the color gradient
      scale_fill_gradient(low = "#deebf7", high = "#3182bd") +
      # Move the x axis to top
      scale_x_discrete(position = "top") + 
      # Remove the grey background
      theme_bw() +
      theme(
        # Remove the border
        panel.border = element_blank(),
        # Rotate the x-axis label to 30 degree
        axis.text.x = element_text(angle = 30)
      )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-31
      • 2019-12-02
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-26
      相关资源
      最近更新 更多