2016-08-01 108 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