我希望构建一个绘图,基本上与我使用ggplots'stat_bin2d'层生成的绘图相同,但是不是将计数映射到变量,我希望与bin关联的计数显示为每个bin的标签.
我从另一个线程得到了等效的1D问题的以下解决方案
data <- data.frame(x = rnorm(1000), y = rnorm(1000))
ggplot(data, aes(x = x)) +
stat_bin() +
stat_bin(geom="text", aes(label=..count..), vjust=-1.5)
Run Code Online (Sandbox Code Playgroud)
每个垃圾箱的计数都有明确标记.然而,从1D变为2D情况,这是有效的,
ggplot(data, aes(x = x, y = y)) +
stat_bin2d()
Run Code Online (Sandbox Code Playgroud)
但这会返回错误.
ggplot(data, aes(x = x, y = y)) +
stat_bin2d() +
stat_bin2d(geom="text", aes(label=..count..))
Error: geom_text requires the following missing aesthetics: x, y
Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个热图,显示驱动每个单元格中颜色的值。如果一个单元格因为有 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)) + …Run Code Online (Sandbox Code Playgroud)