Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R ggplot道奇不分组条_R_Ggplot2 - Fatal编程技术网

R ggplot道奇不分组条

R ggplot道奇不分组条,r,ggplot2,R,Ggplot2,为什么道奇参数不为每个组创建多个条?我想要的是一个分组的条形图,而不是我得到的堆叠的 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 d

为什么道奇参数不为每个组创建多个条?我想要的是一个分组的条形图,而不是我得到的堆叠的

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")
我的结果:

我想要的是:


我想你需要在你的数据框中有一列来区分不同的值,我猜。然后将该列映射到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\u dodgewidth=0.9行是必需的,因为geom\u文本必须以指定的宽度手动进行减淡。

我想您的数据帧中需要一列,它可以实际区分不同的值。我猜了一下。然后将该列映射到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\u dodgewidth=0.9行是必需的,因为geom\u文本必须以指定的宽度手动进行减淡。

我测试了你的代码,但没有得到我要找的分组条形图。我用一个例子更新了我的代码,如果我的请求不明确,我道歉。我使用了你发布的例子数据,在我的答案中添加了代码,得到了一个闪避条形图。你能解释一下用示例数据运行我的代码会得到什么样的结果,这样我就可以确定哪里出了问题吗?我的错-我没有注意到我们使用了两个不同的列作为df$响应。当你使用response时,我是根据group变量来计算的。我测试了你的代码,但是没有得到我想要的分组条形图。我用一个例子更新了我的代码,如果我的请求不明确,我道歉。我使用了你发布的例子数据,在我的答案中添加了代码,得到了一个闪避条形图。你能解释一下用示例数据运行我的代码会得到什么样的结果,这样我就可以确定哪里出了问题吗?我的错-我没有注意到我们使用了两个不同的列作为df$响应。当您使用response时,我将其基于组变量