# 为什么注释会影响每个bin中的密度数？

##### 问题描述投票：0回答：1

ggplot(gb, aes(x = Y*100, y = Y1*100, fill = typeoft)) +
geom_bin2d(bins = 10, aes(alpha = ..count..)) +
scale_fill_manual(values = c("black","red")) +
geom_text_repel(bins = 10,stat = "bin2d",
aes(label = round(100*..density..,1)),
size = 2,direction = "y") +
facet_wrap(~type, nrow = 1) +
geom_abline(slope=1, intercept=0) +
scale_alpha_continuous(range = c(.05,1)) +
theme(panel.background = element_rect(fill = "white")) +

ggplot(gb, aes(x = Y*100, y = Y1*100, fill = typeoft)) +
geom_bin2d(bins = 10, aes(alpha = ..count..)) +
scale_fill_manual(values = c("black","red")) +
geom_text(bins = 10,stat = "bin2d",
aes(label = round(100*..density..,1)),
size = 2,check_overlap = TRUE) +
facet_wrap(~type, nrow = 1) +
geom_abline(slope=1, intercept=0) +
scale_alpha_continuous(range = c(.05,1)) +
theme(panel.background = element_rect(fill = "white")) +
theme(legend.position = "none") +
annotate(geom = "text",label = c(.1,0,.3),x = -.87,y=-.75,size = 2) +
annotate(geom = "text",label = c(.2,.1,1),x = -.29,y=-.18,size = 2)
r ggplot2
##### 1个回答
1

library(tidyverse)
library(ggrepel)
library(grid.arrange)

# Function to generate plot components
pfnc = function(bins, title) {
list(geom_bin2d(bins = bins, aes(alpha = ..count..)),
scale_fill_manual(values = c("black","red")),
geom_text(bins = bins, stat = "bin2d", seed=2,
aes(label = round(100*..density..,1)),
size = 2, direction = "y"),
facet_wrap(~type, nrow = 1),
geom_abline(slope=1, intercept=0),
scale_alpha_continuous(range = c(.5,1)),
theme(panel.background = element_rect(fill = "white")),
theme(legend.position = "none"),
labs(title=title),
scale_x_continuous(limits=range(gb\$Y*100) + c(-0.15,0.15)*diff(range(gb\$Y*100)), expand=c(0,0)),
scale_y_continuous(limits=range(gb\$Y1*100) + c(-0.15,0.15)*diff(range(gb\$Y1*100)), expand=c(0,0))
)
}

p1 = ggplot(gb, aes(x = Y*100, y = Y1*100, fill = typeoft)) +
pfnc(10, "original plot")

p2 = ggplot(gb, aes(x = Y*100, y = Y1*100, fill = typeoft)) +
pfnc(10, "with annotations") +
annotate(geom = "text",label = c(.1,0,.3),x = -.87,y=-.75,size = 4, colour="lightblue") +
annotate(geom = "text",label = c(.2,.1,1),x = -.29,y=-.18,size = 4, colour="lightblue")

grid.arrange(p1, p2, ncol=1)