我希望构建一个绘图,基本上与我使用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)
在更新的版本中ggplot这是完全可能的,并且可以正常工作.
只要确保你使用相同的参数来调用stat_bin2d().例如,binwidth = 1在两行上设置:
library(ggplot2)
data <- data.frame(x = rnorm(1000), y = rnorm(1000))
ggplot(data, aes(x = x, y = y)) +
geom_bin2d(binwidth = 1) +
stat_bin2d(geom = "text", aes(label = ..count..), binwidth = 1) +
scale_fill_gradient(low = "white", high = "red") +
xlim(-4, 4) +
ylim(-4, 4) +
coord_equal()
Run Code Online (Sandbox Code Playgroud)
我无意中回答了你的问题,写了我自己的问题。我发现当您将要分箱的变量从数字转换为文本时, stat_bin2d 将起作用,因此:
library(ggplot2)
data <- data.frame(x = rnorm(1000), y = rnorm(1000))
x_t<-as.character(round(data$x,.1))
y_t<-as.character(round(data$y,.1))
x_x<-as.character(seq(-3,3),1)
y_y<-as.character(seq(-3,3),1)
data<-cbind(data,x_t,y_t)
ggplot(data, aes(x = x_t, y = y_t)) +
geom_bin2d() +
stat_bin2d(geom="text", aes(label=..count..))+
scale_x_discrete(limits =x_x) +
scale_y_discrete(limits=y_y)
Run Code Online (Sandbox Code Playgroud)
所以就这样吧。不幸的是,您必须在 ggplot() 之外设置 binwidths,因此这不是一个理想的解决方案。我不知道为什么当你将变量转换为文本时它会起作用,但它就是这样。
| 归档时间: |
|
| 查看次数: |
1757 次 |
| 最近记录: |