【问题标题】:loop plotting from data set从数据集循环绘图
【发布时间】:2014-08-12 12:22:06
【问题描述】:

我有这个数据集:

x <- sample(80)
matrix <- matrix(x, ncol=5, nrow=16)
matrix <- cbind(matrix, c(rep("group1",4), rep("group2",4), rep("group3",4), rep("group4",4)))
colnames(matrix) <- c(letters[1:5], "groups")
df <- as.data.frame(matrix)

我希望能够使用 for 循环绘制五个箱线图,从 a 到 e 的每一列一个。 我已经尝试过了,但我不知道如何使它工作:

for(i in df[,1:5]) {
  p <- ggplot(df, aes(x=groups, y=as.numeric(as.character(i))))
  p +  geom_boxplot()
}

【问题讨论】:

    标签: r for-loop plot


    【解决方案1】:

    我猜这里:

    library(reshape)
    ggplot(melt(df, id.vars="groups")) + geom_boxplot(aes(x=groups, y=as.numeric(value))) + facet_wrap(~variable)
    

    给予

    library(reshape)
    ggplot(melt(df, id.vars="groups")) + geom_boxplot(aes(x=groups, y=as.numeric(value)), color=variable)
    

    给予

    这是否接近你想要的?

    【讨论】:

    • 例如1:有没有办法在每个情节中保留组名?
    • @Sergio.pv 是的,在这种特殊情况下,使用facet_wrap(~variable, scales="free_x")
    • @Sergio.pv 您可能想查看cookbook 了解更多信息。
    • 有没有办法为构面添加一般标题?我在食谱中找不到答案。
    • @Sergio.pv 见here+ labs(title="test")
    猜你喜欢
    • 2020-01-03
    • 1970-01-01
    • 2021-08-11
    • 2020-10-31
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多