R ggplot geom_栏按组为0值留空格

R ggplot geom_栏按组为0值留空格,r,ggplot2,R,Ggplot2,下面是一个简单的ggplot条形图: x<-c(1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3) y<-c(1,2,3,4,5,3,3,3,3,4,5,5,6,7,6,5,4,3,2,3,4,5,3,2,1,1,1,1,1) d<-cbind(x,y) ggplot(data=d,aes(x=x,fill=as.factor(y)))+ geom_bar(posit

下面是一个简单的ggplot条形图:

x<-c(1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3)
    y<-c(1,2,3,4,5,3,3,3,3,4,5,5,6,7,6,5,4,3,2,3,4,5,3,2,1,1,1,1,1)
    d<-cbind(x,y)
    
    ggplot(data=d,aes(x=x,fill=as.factor(y)))+
      geom_bar(position = position_dodge())

x解决方案是手动计算频率,并根据频率表绘制图表

library(ggplot2)

d1 <- data.frame(table(d))
d1$x <- factor(d1$x)

ggplot(d1, aes(x, Freq, fill = factor(y))) +
  geom_bar(stat = "identity", position = position_dodge())
库(ggplot2)
d1

库(tidyverse)
#设定因子水平
d2%data.frame()%%>%变异(x=因子(x,级别=c(1:3)),
y=系数(y,水平=c(1:7)))
#计算频率并发送到ggplot2
d2%%>%group_by(x,y,.drop=F)%%>%tally()%%
ggplot(aes(x=x,y=n,fill=y,color=y))+
几何杆(位置=位置2(),
stat=“identity”)
使用dplyr实现这一点的另一种方法是使用
tally()
来计算频率,但您需要确保首先将变量设置为因子

aes
语句中使用
color=y
fill=y
有助于准确显示零值在绘图上的位置。现在你可以看到,x=1&x=3缺少y=6&y=7,x=2缺少y=1


我选择了
position\u dodge2
作为我个人的偏好。

我运行你的代码时出错了。我作为输出得到的表没有列“x”,只有列d和列Freq。您是在R的V3或V4实例上吗?我知道新版本的Cbind有一些变化,明白了。R的V4需要data.frame(cbind(x,y))@TannerPhillips不,不要使用构造
data.frame(cbind(.)
。在这种情况下,没有区别,但如果其中一个向量不是数字,这两个向量都将强制为字符,因为
cbind
创建了一个矩阵,而矩阵只能有一种类型的数据
library(tidyverse)

# set factor levels
d2 <- d %>% data.frame() %>% mutate(x=factor(x, levels=c(1:3)), 
             y=factor(y, levels=c(1:7))) 

# count frequencies and send to ggplot2
d2 %>% group_by(x, y, .drop=F) %>% tally() %>% 
  ggplot(aes(x=x, y=n, fill=y, color=y)) + 
  geom_bar(position = position_dodge2(), 
           stat="identity")