使用基于密度的梯度在 R 中创建条形图

Create barplot in R with gradient based on density

我想像在箱线图、小提琴图或蜂群中那样表示多个变量的密度。但在这种情况下,每个变量都是一个带,密度显示为沿条形的渐变。

希望我不需要手动绘制条形作为填充形状。

想象一下,如果不是小提琴图或箱线图,而是带有代表密度的梯度的条形图。

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)

符合要求吗?