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
,df
等异常值,比例尺x会拉伸,从而使密度线不可见。
是否可以通过facet
或quantile(facet,c(0.01,0.99))
来对xlim = quantile(facet, c(0.01,0.99))
进行子集划分,以排除规模异常值?
答案 0 :(得分:2)
您可以在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
然后只使用您的旧代码。我做了一点修改,而是在这里使用基数R的stack
与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))
答案 1 :(得分:1)
我们可以根据filter
为每个value
quantile
key
,然后作图
library(tidyverse)
df %>%
gather %>%
group_by(key) %>%
filter(value > quantile(value, 0.01) & value < quantile(value, 0.99)) %>%
ungroup %>%
ggplot() +
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")