簡體   English   中英

來自帶有條件的融化數據幀的同一層中具有ggplot2的多個箱形圖

[英]Multiple boxplots with ggplot2 in the same layer from a melted data frame with a condition

[txt文件中]有一些數據這些數據已讀入數據框,

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

接下來,我使用以下代碼融化該數據幀,

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

現在,我想將此數據繪制為僅顯示x>0值的箱線圖,因此我使用以下代碼,

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

但是結果圖如下所示,

箱線圖的輸出

但是,我需要的是在同一繪圖圖層中僅將x的正值顯示為單個箱形圖。 有人可以建議我需要在上述代碼中進行更改以獲取正確的輸出,謝謝。

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

您需要對數據框進行子集刪除,以消除不想要的值。 現在,您正在繪制value > 0 ,即TRUE或FALSE,而不是僅繪制value > 0的值的箱形圖。

根據@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

在此處輸入圖片說明

我改善了答案,如果將es中的顏色分配為融化數據幀中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

輸出圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM