【问题标题】:Multiple boxplots with ggplot2 in the same layer from a melted data frame with a condition来自具有条件的熔化数据帧的同一层中具有 ggplot2 的多个箱线图
【发布时间】:2014-02-24 11:17:42
【问题描述】:

我有一些数据here [在一个 .txt 文件中] 我读入了一个数据框,

mydf <- read.table("data.txt", header=T,sep="\t")

接下来我使用以下代码融化这个数据框,

df_mlt <-melt(mydf, id=names(mydf)[1], variable = "cols")

现在我想将此数据绘制为仅显示 x&gt;0 值的箱线图,因此为此我使用以下代码,

plt_bx <-   ggplot(df_mlt, aes(x=ID1,y=value>0, color=cols))+geom_boxplot()

但结果图如下所示,

但是,我需要的是仅将 x 的正值显示为同一绘图层中的单个箱形图。有人可以建议我在上面的代码中需要更改什么以获得正确的输出,谢谢。

【问题讨论】:

    标签: r ggplot2 boxplot melt


    【解决方案1】:
    plt_bx <- ggplot(subset(df_mlt, value > 0), aes(x=ID1,y=value, color=cols)) + geom_boxplot()
    

    您需要对数据框进行子集化以删除不需要的值。现在您正在绘制value &gt; 0,它是 TRUE 或 FALSE,而不是仅包含大于 0 的值的箱线图。

    【讨论】:

    • 感谢您的建议。使用子集中的条件会删除负值。我想为每个 x 变量 ID 显示单独的箱线图
    • @Amm,尝试将group=ID1 添加到aes,但没有您的数据很难更具体。如果您发布数据的代表部分的dput,我可以给您确切的命令。
    • 我在问题的链接中将数据作为 .csv 文件保存
    • @Amm,我更喜欢dput。我的 Excel 认为您的文件有问题。
    • @Amm,正如我之前提到的,如果您使用的是color=cols,并且cols 没有指定实际颜色,而只是一个组,cols 中的组是与ID1中的组相同,则不需要group,只需使用color=cols即可。如果这里描述的条件不满足,那么你就不能使用cols给箱线图上色,至少不能通过aes
    【解决方案2】:

    根据@BrodieG 的建议,以下代码生成如下图,

    plt_bx <- ggplot(subset(df_mlt, value > 0), aes(x=ID1,y=value,group=ID1)) + 
      geom_boxplot(aes(color=ID1),outlier.colour="orangered", outlier.size=3) +
      scale_y_log10(labels = trans_format("log10", math_format(10^.x))) +
      theme_bw() +
      theme(legend.text=element_text(size=14), legend.title=element_text(size=14))+
      theme(axis.text=element_text(size=26)) +
      theme(axis.title=element_text(size=22,face="bold")) +
      labs(x = "x", y = "y", colour="Values") +
      annotation_logticks(sides = "rl")
    plt_bx
    

    【讨论】:

      【解决方案3】:

      我改进了我的答案,如果将 aes 中的颜色分配为熔化数据帧中 id 的一个因素,箱线图的轮廓将显示不同的颜色。即geom_boxplot(aes(color=factor(ID1)))

      以下代码生成如下图,

      plt <- ggplot(subset(df_mlt, value > 0), aes(x=ID1,y=value)) + 
        geom_boxplot(aes(color=factor(ID1))) +
        scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x), labels = trans_format("log10", math_format(10^.x))) +
        theme_bw() +
        theme(legend.text=element_text(size=14), legend.title=element_text(size=14))+
        theme(axis.text=element_text(size=20)) +
        theme(axis.title=element_text(size=20,face="bold")) +
        labs(x = "x", y = "y",colour="legend" ) +
        annotation_logticks(sides = "rl") +
        theme(panel.grid.minor = element_blank()) +
        guides(title.hjust=0.5) +
        theme(plot.margin=unit(c(0,1,0,0),"mm")) 
      plt
      

      【讨论】:

        猜你喜欢
        • 2020-07-22
        • 1970-01-01
        • 2023-03-08
        • 1970-01-01
        • 2023-04-11
        • 1970-01-01
        • 2013-04-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多