一种可能的 Select 是不添加填充 colored颜色 (使用show.legend = FALSE
),例如
library(tidyverse)
set.seed(123)
df <- data.frame(
var_a = rnorm(800),
var_b = rnorm(800),
criteria = rep(c("a", "b", "c", "d", "e", "f", "g", "h"), each = 100)
)
ggplot(df, aes(var_a, var_b)) +
stat_density_2d(aes(fill = after_stat(level)), geom = "polygon",
show.legend = FALSE)+
scale_fill_distiller(palette=1, direction=-1)+
geom_smooth(aes(color = criteria), method = "lm", se = FALSE) +
geom_abline(slope=1, intercept=0, color = "gray35", lwd = 0.3)+
ylab("x label")+
xlab("y_label")+
xlim(-4, 4)+
ylim(-4, 4)
#> `geom_smooth()` using formula = 'y ~ x'
创建于2024-02-05年第reprex v2.1.0页
另一种 Select 是自己指定key_glyph(按https://ggplot2.tidyverse.org/reference/draw_key.html),例如
library(tidyverse)
set.seed(123)
df <- data.frame(
var_a = rnorm(800),
var_b = rnorm(800),
criteria = rep(c("a", "b", "c", "d", "e", "f", "g", "h"), each = 100)
)
ggplot(df, aes(var_a, var_b)) +
stat_density_2d(aes(fill = after_stat(level)), geom = "polygon",
key_glyph = "path")+
scale_fill_distiller(palette=1, direction=-1)+
geom_smooth(aes(color = criteria), method = "lm", se = FALSE) +
geom_abline(slope=1, intercept=0, color = "gray35", lwd = 0.3)+
ylab("x label")+
xlab("y_label")+
xlim(-4, 4)+
ylim(-4, 4)
#> `geom_smooth()` using formula = 'y ~ x'
创建于2024-02-05年第reprex v2.1.0页
或者如果你想要一些不同的东西,你可以制作你自己的字形,例如
library(tidyverse)
set.seed(123)
df <- data.frame(
var_a = rnorm(800),
var_b = rnorm(800),
criteria = rep(c("a", "b", "c", "d", "e", "f", "g", "h"), each = 100)
)
draw_key_stat_2d <- function(data, params, size) {
if (is.null(data$linewidth)) {
data$linewidth <- 0.5
}
lwd <- min(data$linewidth, min(size) / 4)
rectGrob(
width = unit(1, "npc") - unit(lwd, "mm"),
height = unit(1, "npc") - unit(lwd, "mm"),
gp = gpar(
col = "grey20" %||% NA,
fill = radialGradient(colours = c("#00000000", "deepskyblue"),
r1 = 0.2, r2 = 0.8) %||% "grey20",
lty = data$linetype %||% 1,
lwd = lwd * .pt,
linejoin = params$linejoin %||% "mitre",
lineend = params$lineend %||% "butt"
))
}
library(grid)
library(gridExtra)
#>
#> Attaching package: 'gridExtra'
#> The following object is masked from 'package:dplyr':
#>
#> combine
ggplot(df, aes(var_a, var_b)) +
stat_density_2d(aes(fill = after_stat(level)), geom = "polygon",
key_glyph = draw_key_stat_2d)+
scale_fill_distiller(palette=1, direction=-1)+
geom_smooth(aes(color = criteria), method = "lm", se = FALSE) +
geom_abline(slope=1, intercept=0, color = "gray35", lwd = 0.3)+
ylab("x label")+
xlab("y_label")+
xlim(-4, 4)+
ylim(-4, 4)
#> `geom_smooth()` using formula = 'y ~ x'
创建于2024-02-05年第reprex v2.1.0页