如何在r中的热图单元格中显示数值单元格值

时间:2014-10-03 10:15:05

标签: r ggplot2 label heatmap

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

(目的是建立一个信用评级迁移矩阵,其中一个轴是今年的信用评级,另一个是去年的信用评级。输入是一个数据框,其中每一行是一个公司的一个观察,公司的信用评级今年,以及去年的信用评级。矩阵显示哪些公司在两年期间拥有稳定的信用评级,评级较低,并且评级较高。

这是数据和代码

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")         

1 个答案:

答案 0 :(得分:4)

我会使用stat_bin2d,因此ggplot2会在内部计算计数,并以..count..的名称提供这些计数。

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")

我希望有所帮助。