首页 > 解决方案 > 在 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)

标签: rggplot2gradientboxplotviolin-plot

解决方案


所以这是我从你的问题中得到的最接近的近似值:

# 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)

在此处输入图像描述

这符合要求吗?


推荐阅读