自定义着色分类变量的热图 [英] custom colored heatmap of categorical variables

查看:255
本文介绍了自定义着色分类变量的热图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了很多解决这个问题的方法,只发现了类似的问题,其中描述了类似问题的解决方案,但似乎太复杂了。 p> ggplot2热点地图:对类别使用不同的渐变



我想知道是否有类似问题的另一个EASIER解决方案。



我有一个简单的数据框: p>

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $,主要
3,C,可能,适中
4,D,可能,次要
5,E,稀有,附带
6,F,不太可能,附带
7 ,G,不太可能,附带的

我想从中构建一个热图。这很简单:

  ggplot(df,aes(Impact,Likelihood))+ 
geom_tile(aes(fill = x),color =white)+
geom_text(aes(label = X))



然而,颜色是随机分布的,我想要的是每对(Impact,Likelihood)的自定义颜色。例如,这对货币对(Almost Certain,Catastrophic)应该用红色标出。



我该如何做到这一点?

解决方案

您可以创建另一列作为可能性和影响的组合,并使用命名向量作为 scale_fill_manual
例如,

  df < -  data.frame(X = LETTERS [1:3], 
可能性= c(几乎肯定,可能,可能),
影响= c(灾难性,主要,中等),
stringsAsFactors = FALSE )
df $ color < - paste0(df $ Likelihood, - ,df $ Impact)

ggplot(df,aes(Impact,Likelihood))+ geom_tile(aes(fill =color),color =white)+ geom_text(aes(label = X))+
scale_fill_manual(values = c(几乎某些灾难=红色,可能 - 主要= ,Possible-Moderate=blue))


I have searched a lot for a solution to this problem, and only found this similar question where the solution for a similar problem is described but seems to be too complicated.

ggplot2 heatmaps: using different gradients for categories

I would like to know if there is another EASIER solution for a similar problem.

I have a simple dataframe:

,X,Likelihood,Impact
1,A,Almost Certain,Catastrophic
2,B,Likely,Major
3,C,Possible,Moderate
4,D,Likely,Minor
5,E,Rare,Incidental
6,F,Unlikely,Incidental
7,G,Unlikely,Incidental

From which I want to build a heatmap. This is straightforward using:

ggplot(df, aes(Impact, Likelihood)) + 
  geom_tile(aes(fill = X), colour = "white") + 
  geom_text(aes(label = X))

However, the color are distributed randomly, what I want to have is a custom color for each pair of (Impact, Likelihood). E.g., the tile for the pair (Almost Certain, Catastrophic) should be colored in 'red'.

How can I achieve this?

解决方案

You can create another column as the combination of likelihood and impact, and use named vector as the colors in scale_fill_manual For example,

df <- data.frame(X = LETTERS[1:3], 
                 Likelihood = c("Almost Certain","Likely","Possible"), 
                 Impact = c("Catastrophic", "Major","Moderate"), 
                 stringsAsFactors = FALSE)
df$color <- paste0(df$Likelihood,"-",df$Impact)

ggplot(df, aes(Impact, Likelihood)) + geom_tile(aes(fill = color),colour = "white") + geom_text(aes(label=X)) +
  scale_fill_manual(values = c("Almost Certain-Catastrophic" = "red","Likely-Major" = "yellow","Possible-Moderate" = "blue"))

这篇关于自定义着色分类变量的热图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆