2016-08-01 76 views
0

我想制作一个热图,它创建一组清晰度为&的颜色组合作为X轴并切割为Y轴。热图将基于清晰度+颜色的计数以及其与切割的交点进行着色。Ggplot热图 - 用于定制计数范围的自定义颜色

library(ggplot2) 
library(dplyr) 

## rename diamonds df 
# 1. Generate a count for the frequency of cut+clarity 
# 2. Make a heatmap of this using the following bins 
# 3. Red <= 100 Frequency 
      Yellow = between (100 and 500) 
      Green > 500 
# place counts inside the cell: 

df = diamonds %>% 
select(cut, clarity) %>% 
group_by(cut,clarity)%>% 
mutate(count = n()) 

myplot = ggplot(df, aes(x = clarity, y=cut)) + 
geom_bin2d(bins = c(100,500,50000), col='orange') # 
geom_text(aes(label = count),col='red') 

myplot 
+0

使用'切()'为 “离散化” 的连续变量,然后使用自定义比例指定这样你的颜色这样的问题:HTTP ://stackoverflow.com/questions/26103140/how-can-i-create-a-custom-colour-scale-using-ggplot2-and-geom-tile/26103786#26103786或这一个:http:// stackoverflow。 COM /问题/ 10981324/GGPLOT2-热图与 - 颜色换范围值/ 10982332#10982332。不要打扰geom_bin2d,这对分箱x和y值非常有帮助,但您已经有了离散值。 – MrFlick

回答

0

试试这个:

df$col <- cut(df$count,breaks = c(-Inf,100,500,Inf),right = TRUE) 
df$color<-df$col 
levels(df$color) <- c("<=100","100<#<=500",">500") 

ggplot(data = df, aes(x = clarity, y = cut)) + 
    geom_tile(aes(fill = df$color), colour = "white") + 
    scale_fill_brewer("Count",palette = "Set1")+ 
geom_text(aes(label = count),col='yellow',cex=3) 

![enter image description here