ggplot闪避不分组吧

Ril*_*n42 -1 r ggplot2

为什么dodge参数不为每个组创建多个条形图?我正在寻找一个分组的条形图,而不是我得到的堆积条形图.

df<-data.frame(c(40,23,18,41,15,14,38,21,1),c(rep("Do you agree with \nthe 'Hands Up' protestors ?",3),rep("Have the Police alienated themselves\n from the Public?",3),rep("Are the public ignoring the\n dangers Police face everyday?",3)),c("49%","28%","22%","59%","21%","20%","63%","35%","2%"),c(1,1,1,2,2,2,3,3,3))
colnames(df)<-c("values","names","percentages","group")



ggplot(df,aes(names,values,group=group))+
  geom_bar(stat = "identity",position = "dodge",fill=rep(c("green","red","orange"),3))+
  geom_text(aes(label=percentages))+
  ylab("number of votes")+
  xlab("")+
  ggtitle("Police Opinion polls")
Run Code Online (Sandbox Code Playgroud)

我的结果:

在此输入图像描述

我想要的是:

在此输入图像描述

Mar*_*ius 5

我认为你的数据框中需要一个列,它实际上区分了不同的值(我做了一个猜测).然后将该列映射到aes()调用中的填充美学,ggplot以便正确避开值:

df$response = rep(c("Yes", "No", "Unsure"), 3)

dodger = position_dodge(width = 0.9)
ggplot(df,aes(names,values, fill = response))+
    geom_bar(stat = "identity",position = dodger)+
    geom_text(aes(label=percentages), position = dodger)+
    ylab("number of votes")+
    xlab("")+
    ggtitle("Police Opinion polls")
Run Code Online (Sandbox Code Playgroud)

dodger = position_dodge(width = 0.9)行是必需的,因为geom_text必须以指定的宽度手动躲避.

  • 我使用了您发布的示例数据,在我的答案中添加了代码并得到了一个躲闪的条形图.你能解释一下你用我的代码数据运行代码得到的结果吗?这样我就可以确定哪里出错了? (2认同)