r - 如何根据数量更改ggplot中每个方面的xlim或比例?

标签 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

由于df中存在10000.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")

结果

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

关于r - 如何根据数量更改ggplot中每个方面的xlim或比例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55805991/

相关文章:

r - 如何使用 POS 标记的正则表达式提取字符串

r - R 中的上标图例文本

r - 在 geom_boxplot 中添加标准误差作为阴影区域而不是误差条

image - 将 (SVG-) 图像添加到 R 中的现有图形

r - 在自定义引擎中匹配 knitr 文档环境

r - 使用 lubridate 根据日期创建因子

r - ggplot aes_string 不适用于空格

RPostgreSQL 访问数据库,错误 : unable to find an inherited method for function "show", 签名 "PostgreSQLConnection"

r - 在ggplot中结合条形图和散点图

r - ggplot错误的颜色分配