如果我们在散点图上使用
ggplot2
和 ggExtra
,则 ggMarginal
将添加边缘直方图,但仅适用于 X 和 Y 维度。
我想在颜色图例上添加直方图。假设我们有 3 个维度,
x
,y
,z
。散点图将 x
、y
显示为位置,然后将 z
显示为颜色。然后我们就有了关于点颜色的图例。有没有办法在图例中添加直方图,以便观看者可以看到相对频率,而不仅仅是从颜色的视觉解释中猜测?
起点:
x = c(rnorm(100, 2, 2), rnorm(100, -1, 3))
y = c(rnorm(100, -1, 3), rnorm(100, 2, 1))
z = c(rnorm(50, -2, 2), rnorm(100, 1, 1), rnorm(50, 3, 2))
d = data.frame(x, y, z)
library(ggplot2)
ggplot(d, aes(x = x, y = y, color = z)) + geom_point() + scale_color_viridis_c()
我想在
z
的图例中添加直方图。知道怎么做吗?
也许像这样,使用拼凑而成的旋转
geom_histogram
可用空间宽度的任意1/6?
library(patchwork)
library(ggplot2)
library(scales)
x = c(rnorm(100, 2, 2), rnorm(100, -1, 3))
y = c(rnorm(100, -1, 3), rnorm(100, 2, 1))
z = c(rnorm(50, -2, 2), rnorm(100, 1, 1), rnorm(50, 3, 2))
d = data.frame(x, y, z)
p1 <- ggplot(d, aes(x = x, y = y, color = z)) +
geom_point(show.legend = F) +
scale_color_viridis_c()
p2 <- ggplot(d, aes(y = z, fill = after_stat(y))) +
geom_histogram(show.legend = F, bins = 21) +
scale_fill_viridis_c() +
scale_y_continuous(breaks = pretty_breaks(n = 8)) +
labs(y = "Histogram Legend for z", x = NULL) +
theme(
panel.background = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
)
p1 + p2 + plot_layout(widths = c(5, 1))
创建于 2024-04-28,使用 reprex v2.1.0