本文介绍了根据密度在R中创建条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想像在箱线图,小提琴图或蜂群中一样表示多个变量的密度.但是在这种情况下,每个变量都是一个条带,密度沿条形显示为渐变.
I want to represent the density of a number of variables as you would in a boxplot, violin plot, or beeswarm. But in this case, each variable would be a band with the density displayed as a gradient along the bar.
希望我不需要手动将条形图绘制为实心形状.
Hopefully I don't need to manually draw bars as filled shapes.
想象一下,如果不是小提琴或箱形图,而是有一个代表密度的渐变条.
Imagine if instead of the violins or boxplots, there was a bar with a gradient representing the 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)
推荐答案
所以,这是我从您的问题中得到的最近似的结果:
So this is my closest approximation of what I got from your question:
# 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)
符合要求吗?
这篇关于根据密度在R中创建条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!