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")
上述脚本的输出如下:
由于df
中存在1000
、0.07
等离群值,尺度x被拉伸(stretch),导致密度线不可见。
有没有办法通过quantile(facet,c(0.01,0.99))
或xlim = quantile(facet, c(0.01)对
排除比例中的异常值?facet
进行子集化,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
然后就使用你的旧代码。我对其进行了一些修改,而是使用基本 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))
关于r - 如何根据数量更改ggplot中每个方面的xlim或比例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55805991/