如何基于quantitle更改ggplot中每个方面的xlim或缩放?

时间:2019-04-23 07:09:33

标签: r ggplot2

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")

以上脚本的输出如下:

enter image description here

对于1000中有0.07df等异常值,比例尺x会拉伸,从而使密度线不可见。

是否可以通过facetquantile(facet,c(0.01,0.99))来对xlim = quantile(facet, c(0.01,0.99))进行子集划分,以排除规模异常值?

2 个答案:

答案 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的stackgather相同,以避免必须加载过多的附加包。

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")

结果

enter image description here

数据

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")

enter image description here

相关问题