[英]How to create a plot of two variables in a melted data frame in ggplot2?
[英]Multiple boxplots with ggplot2 in the same layer from a melted data frame with a condition
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.