r - 如何根据数量更改ggplot中每个方面的xlim或比例?
问题描述
library(tidyr)
library(ggplot2)
df <- data.frame(a = as.numeric(c(1, 2, 3, 4, 5, 6)),
b = as.numeric(c(1, 3, 3, 5, 10, 1000)),
c = as.numeric(c(0.07, 0.09, 6, 9, 10, 30)))
ggplot(gather(na.omit(df)), aes(x = value, y = ..density..))+
geom_histogram(bins = 5, colour = "black", fill = "white") +
facet_wrap(~key, scales = 'free_x')+
scale_x_continuous(breaks = scales::pretty_breaks(5))+
geom_density(alpha = .2, fill = "#FF6666")
上述脚本的输出如下:
至于有1000
, 0.07
in等异常值df
, 尺度 x 被拉伸, 使密度线不可见。
有没有办法按比例进行子集facet
化quantile(facet,c(0.01,0.99))
,或xlim = quantile(facet, c(0.01,0.99))
排除规模上的异常值?
解决方案
您可以在sapply
.
df2 <- as.data.frame(sapply(df1, function(x){
qu <- quantile(x, c(0.01, 0.99))
x[which(x > qu[1] & x < qu[2])]}))
df2
# a b c
# 1 2 3 0.09
# 2 3 3 6.00
# 3 4 5 9.00
# 4 5 10 10.00
或者,使用data.table::between
,这对间隔很有用。
library(data.table)
df2 <- as.data.frame(sapply(df1, function(x)
x[which(x %between% quantile(x, c(0.01, 0.99)))]))
df2
# a b c
# 1 2 3 0.09
# 2 3 3 6.00
# 3 4 5 9.00
# 4 5 10 10.00
然后只需使用您的旧代码。我对其进行了一些调整,而是stack
在此处使用 base R,它的作用与gather
避免加载过多的附加包相同。
library(ggplot2)
ggplot(stack(na.omit(df2)), aes(x=values, y=..density..)) +
geom_histogram(bins=5, colour="black", fill="white") +
facet_wrap(~ind, scales='free_x') +
scale_x_continuous(breaks=scales::pretty_breaks(5)) +
geom_density(alpha=.2, fill="#FF6666")
结果
数据
df1 <- structure(list(a = c(1, 2, 3, 4, 5, 6), b = c(1, 3, 3, 5, 10,
1000), c = c(0.07, 0.09, 6, 9, 10, 30)), class = "data.frame", row.names = c(NA,
-6L))
推荐阅读
- sql - Oracle,从另一个查询(不同)中获取 Rowid,并使用 rowid 选择值
- angular - 在 Angular 8 单页应用程序中重新渲染 FirebaseUI Auth 小部件不起作用
- excel - 具有多个条件和 OR 条件的 COUNTIFS
- c - 共享文件夹中 fopen() 的 mingw 错误
- azure-devops - VssServiceResponseException:在 Azure Pipelines 中被禁止
- c++ - 如何将嵌套在通过参数包实例化的类模板中的可变别名模板作为模板模板参数传递?
- node-red - 我该如何解决:Node RED App not deploying
- sql - Conditional join on soonest date - SQL Server 2017
- flutter - 升级 Flutter 项目 - 复制原生文件?
- r - 如何让 R 包 Openair 中的 rollingMean 函数工作?