gpt4 book ai didi

从 R 中使用 ggplot2 制作的多个箱线图中完全删除异常值并以扩展格式显示箱线图

转载 作者:行者123 更新时间:2023-12-04 00:01:18 24 4
gpt4 key购买 nike

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

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

我删除列中的负值 x (因为我只需要正值)的 df使用以下代码,
yp <- subset(df, x>0)

现在我想在同一层绘制多个箱线图。我先把数据框融化 df ,结果图包含几个异常值,如下所示。
# Melting data frame df    
df_mlt <-melt(df, id=names(df)[1])
# plotting the boxplots
plt_wool <- 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_wool

Boxplot with outliers

现在我需要一个没有任何异常值的图,所以首先我计算下限和上限 mustache 我按照建议使用以下代码 here ,
sts <- boxplot.stats(yp$x)$stats

为了删除异常值,我添加了上下晶须限制,如下所示,
p1 = plt_wool + coord_cartesian(ylim = c(sts*1.05,sts/1.05))

结果图如下所示,而上面的代码行正确删除了大部分顶部异常值,所有底部异常值仍然存在。有人可以建议如何从该图中完全删除所有异常值,谢谢。

enter image description here

最佳答案

一个最小的可重现示例:

library(ggplot2)
p <- ggplot(mtcars, aes(factor(cyl), mpg))
p + geom_boxplot()

不绘制异常值:
p + geom_boxplot(outlier.shape=NA)
#Warning message:
#Removed 3 rows containing missing values (geom_point).

(我更喜欢收到这个警告,因为一年后用一个长脚本它会提醒我我在那里做了一些特别的事情。如果你想避免它,请使用 Sven 的解决方案。)

关于从 R 中使用 ggplot2 制作的多个箱线图中完全删除异常值并以扩展格式显示箱线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21533158/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com