使用ggplot绘制2种不同因素的所有列的分布?

问题描述 投票:0回答:1

我有一个可以按如下方式生成的数据框:

DD <- data.frame(group = c(rep("A", 5), rep("B", 6)), Feat1 = rnorm(11), feat2 = rnorm(11,3,5), feat3 = rnorm(11), feat4 = rnorm(11,2,3))

我想绘制列为group的2个因素(A和B)的每个列特征的分布。即我想对列feat1,feat2等有4个图,其中每个列都有A组和B组的2个分布图。我想一次在一个框架中有4个图。

您知道如何使用ggplot做到吗?

r ggplot2 plot distribution
1个回答
0
投票

我不是100%地确定您要实现的目标,但我认为,轮换数据应该使您走上正确的道路。如果将所有要素值移到单个列中,则将图分成多个面会更容易。

library(ggplot2)
library(tidyr)

DD2 <- DD %>% 
  pivot_longer(-group, names_to = "feature")

#   group feature  value
#   <fct> <chr>    <dbl>
# 1 A     Feat1    2.17 
# 2 A     feat2   -2.69 
# 3 A     feat3    3.07 
# 4 A     feat4    0.848
# 5 A     Feat1   -2.00 
# 6 A     feat2   -4.96 
# 7 A     feat3    0.798
# 8 A     feat4   -2.96 
# 9 A     Feat1   -1.65 
#10 A     feat2    3.45
# ... with 34 more rows

我们现在可以通过功能列轻松地将图刻面:

DD2 %>%
  ggplot(aes(x = group, y = value)) +
  geom_boxplot() + # Also works with geom_violin(), geom_jitter() etc.
  facet_grid(~feature)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.