构面的每个图都有不同的Binwidth [英] Different Binwidth for Each Plot of a Facet

查看:519
本文介绍了构面的每个图都有不同的Binwidth的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图了解为geom_histogram中的每个因子级别分配唯一的binwidth. 到目前为止,失败了.

Trying to understand assigning unique binwidth for each factor level in geom_histogram. So far failed though.

这是可复制的数据

a <- rnorm(10,7,0.1)
b <- rnorm(10,13,5)
df <- data.frame(data = c(a,b),group=c(rep("a",10),rep("b",10)))
kk <- df%>%
  group_by(group)%>%
  mutate(bin=density(data)$bw)

binns <- round(unique(kk$bin),digits = 2)  # to get each binwidth for each group

ggplot()+
  geom_histogram(data=kk,aes(x=data, fill=group),binwidth=binss)+
  facet_wrap(~group,scales=c("free_y"))

Error in seq.default(round_any(range[1], size, floor),    round_any(range[2],  : 
  'from' must be of length 1
Error in seq.default(round_any(range[1], size, floor), round_any(range[2],  : 
  'from' must be of length 1
Error in exists(name, envir = env, mode = mode) : 
  argument "env" is missing, with no default

然后我尝试了

ggplot()+
  geom_histogram(data=kk,aes(x=data, fill=group),binwidth=c(binns[1],binns[2]))+
  facet_wrap(~group,scales=c("free_y"))

发生相同的错误.我不明白为什么会出现同样的错误.

The same error happened. I couldn't understand why it is giving the same error.

推荐答案

您可以在垃圾箱上迭代以创建图层

You could iterate on bins to create layers

library(dplyr)
a <- rnorm(10,7,0.1)
b <- rnorm(10,13,5)
df <- data.frame(data = c(a,b),group=c(rep("a",10),rep("b",10)))
kk <- df %>%
  group_by(group) %>%
  mutate(bin=round(density(data)$bw, 2))
binns <- unique(kk$bin)

附加ggplot2

library(ggplot2)

在列表中为每个bin值创建一个直方图图层,并仅包含此bin的数据.如果您有30个级别,则将有30个直方图图层的列表

Create in a list one histogram layer per bin value with data only for this bin. If you have 30 level, you'll have a list of 30 histogram layers

lp_hist <- plyr::llply(binns, function(b) {
  geom_histogram(data = kk %>% 
                   filter(bin == b), 
                 aes(x = data, fill=group), 
                 binwidth = b)
  })

合并这些图层,并将其全部添加到ggplot()对象

Combine those layers, adding them all to ggplot() object

p_hist <- Reduce("+", lp_hist, init = ggplot())

根据需要进行缩放和缩放

Facet and scale as you want

p_hist + facet_grid(. ~ group, scales = "free_y")

您将获得想要的图形,即按面表示不同的binwidth.

you'll obtain the graph you want that is to say a different binwidth by facet.

提防,因为30个级别会赋予30个方面...很多.

Watch out because 30 levels will give 30 facets... it is a lot.

注意:在R 3.2.3

这篇关于构面的每个图都有不同的Binwidth的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆