【问题标题】:R/ggplot2: is it possible to boxplot columns from a dataframe without a factor column?R/ggplot2:是否可以在没有因子列的情况下从数据框中绘制列?
【发布时间】:2023-03-08 01:12:01
【问题描述】:

在这里用 ggplot 有点挣扎。正如标题所说:是否可以在没有因子列的情况下从数据框中绘制列?也就是说,使用感兴趣的列的名称作为x?

示例 1(图形)

df <- data.frame(c(0.2, 0.3, 0.4), c(0.4, 0.2, 0.5))
colnames(df) <- c("A1", "A2")
rownames(df) <- c("001", "002", "003")
df

     A1  A2
001 0.2 0.4
002 0.3 0.2
003 0.4 0.5

boxplot(df[,"A1"], df[,"A2"], names=colnames(df))

示例 2 (ggplot2)

library(ggplot2)

df2 <- data.frame(c("A1", "A1", "A1", "A2", "A2", "A2"), c(0.2, 0.3, 0.4, 0.4, 0.2, 0.5))
colnames(df2) <- c("Series", "Value")
df2

  Series Value
1     A1   0.2
2     A1   0.3
3     A1   0.4
4     A2   0.4
5     A2   0.2
6     A2   0.5

p <- ggplot(df2, aes(as.factor(Series), Value)) + geom_boxplot()
p

在第二种情况下,我丢失了不能重复的行名,尽管它们是我需要保留的 ID。那么我可以在 ggplot2 保持第一个数据结构的情况下获得这个结果吗?谢谢

【问题讨论】:

  • 您必须处理第一个结构以获得第二个结构。 ggplot(reshape2::melt(df), aes(x = variable, y = value)) + geom_boxplot()
  • 谢谢,我遇到过这种语法,但我不太明白“值”和“变量”的来源,当我尝试将它应用于我的实际数据时,我得到一个“找不到对象‘变量’”错误。 data_to_plot &lt;- my_data[, c("IC.2", "IC.3", "IC.4")] ggplot(reshape2::melt(data_to_plot), aes(x = variable, y = value)) + geom_boxplot() Using IC.2, IC.3, IC.4 as id variables Error in FUN(X[[i]], ...) : object 'variable' not found
  • 我期待 reshape2::melt(df) 输出类似于经过验证的 anwser here 的内容,但它仍然显示我的 3 列数据,尽管它应该将所有值分组到 1 列中,对吧?

标签: r ggplot2


【解决方案1】:

所以我无法让 reshape2 工作,但是我想出了一个使用 tidyr 包的解决方案:

library(dplyr)
library(tidyr)
library(ggplot2)

df <- data.frame(c(0.2, 0.3, 0.4), c(0.4, 0.2, 0.5))
colnames(df) <- c("A1", "A2")
rownames(df) <- c("001", "002", "003")
df
    A1  A2
001 0.2 0.4
002 0.3 0.2
003 0.4 0.5

tidy_df <- df %>% gather(variable, value, c("A1", "A2"))
p <- ggplot(tidy_df, aes(x = variable, y = value)) + geom_boxplot()
p

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-22
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 2021-12-07
    • 1970-01-01
    相关资源
    最近更新 更多