我已经搜索了很多这个问题的解决方案,并且只找到了类似的问题,其中描述了类似问题的解决方案,但似乎过于复杂。
ggplot2 heatmaps: using different gradients for categories
我想知道是否有另一种类似问题的EASIER解决方案。
我有一个简单的数据框:
,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
我想从中构建热图。这很简单:
ggplot(df, aes(Impact, Likelihood)) +
geom_tile(aes(fill = X), colour = "white") +
geom_text(aes(label = X))
然而,颜色是随机分布的,我想要的是每对(影响,可能性)的自定义颜色。例如,对的瓷砖(几乎是确定的,灾难性的)应该用'红色'着色。
我怎样才能做到这一点?
答案 0 :(得分:2)
您可以创建另一列作为可能性和影响的组合,并使用命名向量作为scale_fill_manual
中的颜色
例如,
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"))
答案 1 :(得分:0)