关于ggplot2:如何在r中的热图单元格中显示数字单元格值

How to show the numeric cell values in heat map cells in r

我正在尝试创建一个热图,以显示驱动每个单元格中颜色的值。如果一个单元格是深蓝色的,因为它有 5 个观察值,我想查看该单元格中的数字 5。

(目的是建立一个信用评级迁移矩阵,其中一个轴是今年的信用评级,另一个是去年的信用评级。输入是一个数据框,其中每一行是一个公司的一个观察,公司\\'今年的信用评级和去年的信用评级。该矩阵显示哪些公司在两年内具有稳定的信用评级,哪些公司的评级较低,哪些公司的评级较高)。

这是数据和代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
require(ggplot2)

# Create a dataframe mm where each row is one observation for one company,
# the company's credit rating this year, and it credit rating last year.  A company ID is
# provided.  


mm<-data.frame(
    CompamyID = c(1:14),
    CurrentYear =c("Aaa","Aa","B","Baa","C","Aaa","Aa","B","Baa","C","Aa","B","Baa","C"),
    PreviousYear=c("Aaa","Aa","B","Baa","Aa","B","Baa","C","C","Aaa","Aa","B","Baa","C"),
    Count=rep(1,14)
)

# Create heatmap and show the number of observations in each cell.  
# I have used label= # sum() for illustration but it is wrong.  

ggplot(data=mm, aes(x = mm$CurrentYear, y=mm$PreviousYear)) +
    geom_bin2d() +
    geom_text(aes(fill = mm$Count, label = sum(mm$Count)))+
    scale_x_discrete(limits =c("Aaa","Aa","A","Baa","Ba","B","Caa","Ca","C")) +
    scale_y_discrete(limits=c("C","Ca","Caa","B","Ba","Baa","A","Aa","Aaa")) +
    scale_fill_gradient2() +
    theme(panel.grid.major = element_line( colour ="white", size = 0.5 ))+
    theme(panel.grid.minor = element_line( colour ="black", linetype ="dashed", size = 0.5)) +
    theme(panel.background = element_rect( colour ="black", fill ="white",size = 1.0 )) +
    ggtitle("MIGRATION MATRIX USING geom_bin2d()") +
    xlab("Current Year") +
    ylab("Previous Year")

我会使用 stat_bin2d,所以 ggplot2 会在内部计算计数并以 ..count.. 的名称提供它们。

1
2
3
4
5
6
7
8
9
10
11
12
ggplot(data=mm, aes(x = mm$CurrentYear, y=mm$PreviousYear)) +
  geom_bin2d() +
  stat_bin2d(geom="text", aes(label=..count..))+
  scale_x_discrete(limits =c("Aaa","Aa","A","Baa","Ba","B","Caa","Ca","C")) +
  scale_y_discrete(limits=c("C","Ca","Caa","B","Ba","Baa","A","Aa","Aaa")) +
  scale_fill_gradient2() +
  theme(panel.grid.major = element_line( colour ="white", size = 0.5 ))+
  theme(panel.grid.minor = element_line( colour ="black", linetype ="dashed", size = 0.5)) +
  theme(panel.background = element_rect( colour ="black", fill ="white",size = 1.0 )) +
  ggtitle("MIGRATION MATRIX USING geom_bin2d()") +
  xlab("Current Year") +
  ylab("Previous Year")

希望对你有帮助。