【问题标题】:Plot discrete values with different color绘制不同颜色的离散值
【发布时间】:2015-12-26 21:27:48
【问题描述】:

给定一个具有离散值的数据框,

d=data.frame(id=1:6, a=c(1,1,1,0,0,0), b=c(0,0,0,1,1,1), c=c(10,20,30,30,10,20))

我想制作一个类似的情节

但是我想为每一层制作不同的颜色,比如“a”为红色和绿色,“b”为黄色/蓝色。

【问题讨论】:

  • 如何确定颜色渐变?从我在图片上看到的a 线上的6 个矩形应该有light blue - light blue - light blue - dark blue - dark blue - dark blue(值是1 1 1 0 0 0
  • 这只是我想要实现的一个随机示例。重点是根据dataframe用不同的颜色填充框。
  • 你试过geom_tile吗?
  • 是的,但我无法为不同的行获得不同的颜色!!
  • 请使用您当前的代码更新您的帖子,即使它不起作用。

标签: r plot ggplot2


【解决方案1】:

我们的想法是重塑您的数据(定义坐标以绘制矩形)以便使用来自ggplotgeom_rect

library(ggplot2)
library(reshape2)

i = setNames(expand.grid(1:nrow(d),1:ncol(d[-1])),c('x1','y1'))

ggplot(cbind(i,melt(d, id.vars='id')), 
       aes(xmin=x1, xmax=x1+1, ymin=y1,  ymax=y1+1, color=variable, fill=value)) + 
       geom_rect()

【讨论】:

    【解决方案2】:

    试试geom_tile()。但是您需要重塑您的数据以获得与您提供的完全相同的数字。

    df  <- data.frame(id=factor(c(1:6)), a=c(1,1,1,0,0,0), b=c(0,0,0,1,1,1), c=c(10,20,30,30,10,20))
        library(reshape2)
    
        df <- melt(df, vars.id  = c(df$id))
    
           library(ggplot2)
            ggplot(aes(x = id, y = variable, fill = value), data = df) + geom_tile() 
    

    【讨论】:

      【解决方案3】:
      require("dplyr")
      require("tidyr")
      require("ggplot2")
      
      d=data.frame(id=1:6, a=c(1,1,1,0,0,0), b=c(0,0,0,1,1,1), c=c(10,20,30,30,10,20))
      
      ggplot(d %>% gather(type, value, a, b, c) %>% mutate(value = paste0(type, value)), 
             aes(x = id, y = type)) +
        geom_tile(aes(fill = value), color = "white") +
        scale_fill_manual(values = c("forestgreen", "indianred", "lightgoldenrod1", 
                                     "royalblue", "plum1", "plum2", "plum3"))
      

      【讨论】:

        【解决方案4】:

        首先我们使用reshape2 将数据从宽转换为长。然后为了获得离散值,我们使用as.factor(value),最后我们使用scale_fill_manual 分配我们需要的5 种不同颜色。在geom_tile 中,我们指定了磁贴边框的颜色。

        library(reshape2)
        library(ggplot2)
        df <- data.frame(id=1:6, a=c(1,1,1,0,0,0), b=c(0,0,0,1,1,1), c=c(10,20,30,30,10,20))    
        df <- melt(df, id.vars=c("id"))
        ggplot(df, aes(id, variable, fill = as.factor(value))) + geom_tile(colour = "white") + 
          scale_fill_manual(values = c("lightblue", "steelblue2", "steelblue3", "steelblue4", "darkblue"), name = "Values")+
          scale_x_discrete(limits = 1:6)
        

        【讨论】:

          猜你喜欢
          • 2020-12-22
          • 1970-01-01
          • 1970-01-01
          • 2021-10-05
          • 1970-01-01
          • 1970-01-01
          • 2011-02-05
          • 1970-01-01
          • 2015-03-29
          相关资源
          最近更新 更多