gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:39:39 24 4
gpt4 key购买 nike

我正在尝试创建一个热图,显示驱动每个单元格中颜色的值。如果一个单元格是深蓝色的,因为它有 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")

最佳答案

我会使用 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")

希望对您有所帮助。

关于r - 如何在 r 中的热图单元格中显示数字单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26177134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com