ggplot闪避不分组吧

时间:2017-09-27 00:27:54

标签: 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")

我的结果:

enter image description here

我想要的是什么:

enter image description here

1 个答案:

答案 0 :(得分: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") 调用中的填充美学,以正确避开这些值:

dodger = position_dodge(width = 0.9)

需要geom_text行,因为.header-image { display: block; width: 100%; text-align: center; /* image must be 1900 x 500 */ background: url('back.1.jpg') no-repeat center center scroll; -webkit-background-size: cover; -moz-background-size: cover; background-size: cover; -o-background-size: cover; opacity: 1.0; } .headline { padding: 120px 0; } .headline h1 { font-size: 50px; font-weight: 500; background: #24292E; background: rgba(36, 41, 46, 0.7); color: #FCFCFC; }必须以指定的宽度手动躲避。