首页 > 解决方案 > 酒吧作为ggplot中的一堆正方形

问题描述

我试图获得一个条形图,其中每个条形由一堆正方形组成,以便更容易计算每个条形上的观察值。这是一个最小的例子

library(ggplot2)
d = data.frame(p = rbinom(20,10,.3))   
d %>% ggplot(aes(x=p))+geom_bar(fill="white",color="black",position="stack",alpha=.5)+
      theme_void()

这给出了类似的东西:

在此处输入图像描述

基本上,我想在条形图的每个单元上都有水平分隔线。

标签: rggplot2geom-bar

解决方案


This approach can be useful:

library(ggplot2)
library(dplyr)
#Data
d = data.frame(p = rbinom(20,10,.3))   
#Plot
d %>%  
  group_by(p) %>%
  mutate(col=row_number()) %>%
  ggplot(aes(x=p,fill=factor(col)))+
  geom_bar(position="stack",alpha=.5,color='black')+
  theme_void()+
  scale_fill_manual(values=rep('white',5))+
  theme(legend.position = 'none')

Output:

enter image description here


推荐阅读