r - 在 R 中使用基于密度的梯度创建条形图
问题描述
我想像在箱线图、小提琴图或蜂群图中一样表示许多变量的密度。但在这种情况下,每个变量将是一个带,其密度显示为沿条形的渐变。
希望我不需要手动将条形绘制为填充形状。
想象一下,如果不是小提琴或箱线图,而是有一个代表密度的渐变条。
library(tidyverse)
library(ggplot)
df = data.frame(
A = 2.3 + 7*rnorm(100),
B = 0 + 5*rnorm(100),
C = 4 + 2*rnorm(100)
)
df %>%
gather() %>%
ggplot(aes(x=key, y=value)) +
geom_violin(scale="width", fill='red', alpha=0.5) +
geom_boxplot(fill='green', alpha=0.5)
解决方案
所以这是我从你的问题中得到的最接近的近似值:
# Dummy data
df <- data.frame(
y = c(rnorm(100, 4), rnorm(100, 12)),
x = rep(c(1, 2), each = 100)
)
ggplot(df, aes(x, y, group = x)) +
# To fill gap between 0 and actual data
stat_summary(geom = "rect",
fun.ymin = function(x){0},
fun.ymax = min,
aes(xmin = x - 0.4, xmax = x + 0.4, fill = 0)) +
# To make the density part
stat_ydensity(aes(fill = stat(density),
xmin = x - 0.4, xmax = x + 0.4,
# Nudge y by a bit depending on the spread of your data
ymin = stat(y) - 0.01, ymax = stat(y) + 0.01),
geom = "rect", trim = FALSE)
这符合要求吗?
推荐阅读
- android - 如何以编程方式获取 youtube 视频的观看次数和点赞次数
- android - 带有 PendingIntent 和 putExtra 的 Java 通知不起作用
- laravel - 如何使用嵌套模型加载 Laravel 并限制嵌套模型?
- openedx - 讲师仪表板中缺少 OpenEdX 的电子邮件选项卡?
- javascript - 用js根据其他单元格填表
- ios - 在 Swift 4 中从 uitextfields 将数据发布到服务器
- docker - 无法使用 traefik 的仪表板绑定到端口 8080
- mysql - mysql 8 远程访问
- security - 这对我的程序中的修改检查有用吗?
- jquery - 将视口可见性与 DrawSVG 相结合