如何在ggplot的geom_bar与geom_histogram中忽略异常值?
解决ggplot中geom_bar异常值导致图表难以解读的问题
首先帮你纠正下原代码里的小语法错误——scale_y_continuous的括号没闭合,而且quantile的第二个参数得是0到1之间的数值,你写的c(0,10)是不符合语法要求的哈。
回到你的问题,针对x轴上的1000这个异常值,有两种实用的解决方式:
方法1:提前过滤异常值再绘图
这是最直接稳妥的方式,先把数据框里choice大于10的观测过滤掉,再传入ggplot绘图:
library(ggplot2) # 过滤数据,仅保留choice ≤10的行 DF_filtered <- DF[DF$choice <= 10, ] ggplot(DF_filtered, aes(choice, 1)) + geom_bar(stat = "identity") + scale_y_continuous(limits = c(0, 10)) + theme(axis.text.x = element_text(angle = 0, hjust = 1), text = element_text(size=20))
方法2:直接设置x轴范围(类似ylim的xlim参数)
如果你不想修改原始数据,可以用xlim()或者scale_x_continuous(limits=...)直接截断x轴,把超出10的部分隐藏起来:
library(ggplot2) ggplot(DF, aes(choice, 1)) + geom_bar(stat = "identity") + xlim(0, 10) + # 直接限定x轴范围,隐藏10以上的数值 scale_y_continuous(limits = c(0, 10)) + theme(axis.text.x = element_text(angle = 0, hjust = 1), text = element_text(size=20))
要是需要更灵活的x轴断点设置,用scale_x_continuous会更合适:
ggplot(DF, aes(choice, 1)) + geom_bar(stat = "identity") + scale_x_continuous(limits = c(0, 10), breaks = seq(0,10,2)) + scale_y_continuous(limits = c(0, 10)) + theme(axis.text.x = element_text(angle = 0, hjust = 1), text = element_text(size=20))
小提醒
你之前提到的ylim是针对y轴的限制参数,而你的异常值出现在x轴(choice是x变量),所以得用对应的xlim或scale_x_continuous来调整范围。另外确实像你说的,geom_boxplot的异常值处理逻辑不适用于bar/histogram类图表,截断或过滤数据是这类场景下更合适的方案。
内容的提问来源于stack exchange,提问作者KaC
相关产品推荐
相关产品推荐

