2015-09-29 182 views
3

鉴于离散值的数据帧的离散值,情节不同颜色的

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

我要让喜欢

enter image description here

不过,我想使不同颜色的每一层的阴谋,对于“a”说红色和绿色,对“b”说黄色/蓝色。

+0

你如何确定颜色渐变?从我在图片上看到的'a'线上的6个矩形应该有'浅蓝 - 浅蓝 - 浅蓝 - 深蓝 - 深蓝 - 深蓝'(数值为'1 1 1 0 0 0') –

+0

这只是我想要实现的一个随机示例。重点是根据datafram填充不同颜色的框。 –

+0

你尝试过'geom_tile'吗? – zx8754

回答

1

的想法是重塑你的数据(定义坐标绘制矩形),以使用geom_rectggplot

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

enter image description here

0

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

enter image description here

0

首先,我们使用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) 

enter image description here

0
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")) 

enter image description here