如何在ggplot中突出观察bin? [英] How to highlight bin of observation in ggplot?

查看:133
本文介绍了如何在ggplot中突出观察bin?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用ggplot突出显示观察 obs.A和obs.B分别正在分配整个酒吧?确切的

  set.seed(12345)
data < - data.frame( Var = c(rep(A,50),rep(B,50)),Value = round(rnorm(10000,10,10),0))
obs.A <-8
obs.B< -10
cond< - (data $ Var =='A'& data $ Value == obs.A)|(data $ Var =='B'& data $ value == obs.B)
binwidth <-0.5
ggplot(data)+
geom_histogram(data = data [!cond,],aes(x = Value),binwidth = binwidth)+
geom_histogram(data = data [cond,],aes(x = Value),fill ='red',binwidth = binwidth)+
facet_grid(Var〜。)


How to highlight the entire bar in which the observations obs.A and obs.B respectively are being allocated using ggplot? The exact same thing has been done for the regular hist() function but what is the ggplot way?

Below some code to illustrate

library(ggplot2)
data <- data.frame(Var=c(rep("A",50),rep("B",50)), Value=round(rnorm(100,10,2),0))
obs.A<-8
obs.B<-10
ggplot(data)+
  geom_histogram(aes(x=Value))+
  facet_grid(Var ~ .)

Edit: It needs to work for large and small sample sizes and really only highlight one and all of the bar.

解决方案

We can try this to have desired the highlighting for any size of data (we may need to adjust the bindwith with the data size for the bar chart to look prettier and more informative):

library(ggplot2)
set.seed(12345)
data <- data.frame(Var=c(rep("A",50),rep("B",50)), Value=round(rnorm(100,10,2),0))
obs.A<-8
obs.B<-10
cond <- (data$Var=='A' & data$Value == obs.A)|(data$Var=='B' & data$Value == obs.B)
binwidth <- 0.25
ggplot(data)+
  geom_histogram(data=data[!cond,], aes(x=Value), binwidth=binwidth) + 
  geom_histogram(data=data[cond,], aes(x=Value), fill='red', binwidth=binwidth) + 
  facet_grid(Var ~ .)

set.seed(12345)
data <- data.frame(Var=c(rep("A",50),rep("B",50)), Value=round(rnorm(10000,10,10),0))
obs.A<-8
obs.B<-10
cond <- (data$Var=='A' & data$Value == obs.A)|(data$Var=='B' & data$Value == obs.B)
binwidth <- 0.5
ggplot(data)+
  geom_histogram(data=data[!cond,], aes(x=Value), binwidth=binwidth) + 
  geom_histogram(data=data[cond,], aes(x=Value), fill='red', binwidth=binwidth) + 
  facet_grid(Var ~ .)

这篇关于如何在ggplot中突出观察bin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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