【问题标题】:Flat lines in ggplot2 boxplot()ggplot2 boxplot() 中的平线
【发布时间】:2021-05-24 12:19:14
【问题描述】:

我正在尝试使用 ggplot2 绘制一些分组箱线图,但我遇到了麻烦,因为箱线图只是显示为平线。

数据框如下:

   col1 col2 col1.1 col2.1 col1.2 col2.2 group 
a  0.1   ...                              G1
b  0.2   ...                              G1
c  0.3   ....                             G2
d  0.3   ....                             G2
e  0.1   ...                              G3
f  0.1   ...                              G3
g  0.1   ...                              G3

列名:col1、col1.1、col1.2、col2、col2.1 和 col2.2 行名:a,b,c,d,e,f,g group 列表示每一行所属的组。

我希望能够分离出每个组,并为每种类型的列绘制箱线图。即,我会将所有 col1、col1.1 和 col1.2 转换为“col1”并为该组绘制箱线图,与 col2 类似。

我的代码如下:

G1 = df[df$group == "G1",]
G1 = G1[,-7]

p = G1[gtools::mixedsort(rownames(G1)),]
p$name = rownames(p)
p = reshape2::melt(p, id.vars="name")
colnames(p) <-c("name","group","values") 
p$group = gsub("\\..*", "" , p$group)
p$group = factor(p$group, levels = c("col1","col2"))

plt1 = ggplot(p, aes(x = factor(group), y = values, fill = name)) + geom_boxplot() + scale_fill_brewer(palette="Set3")  + xlab("group") + ylab("Values") 

但是,使用此代码,我的箱线图中出现了平线。 如果您能发现我的错误,请帮助我。

提前致谢!

【问题讨论】:

  • See here 关于制作一个更易于人们帮助的可重现示例。这还不足以制作有意义的箱线图,而且您的大部分代码似乎都在为绘图做准备——试着给我们一个准备好绘图的数据样本,所以我们专注于调试绘图而不是而不是重塑数据的步骤

标签: r ggplot2


【解决方案1】:

你可以试试这个-

library(tidyverse)

df %>%
  pivot_longer(cols = -group, 
               names_to = '.value', 
               names_pattern = '(col\\d+)') %>%
  pivot_longer(cols = -group) %>%
  ggplot(aes(x = factor(group), y = value, fill = name)) + 
  geom_boxplot() + 
  scale_fill_brewer(palette="Set3")  + 
  xlab("group") + ylab("Values") 

数据

可重现的数据 -

set.seed(123)
df <- data.frame(col1 = rnorm(7), col2 = runif(7), col1.1 = rnorm(7), 
                 col2.1 = rnorm(7), col1.2 = runif(7), col2.2 = rnorm(7), 
                 group = c('G1', 'G1', 'G2', 'G2', 'G3', 'G3', 'G3'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-01
    • 2015-08-24
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多