2017-02-21 111 views
-1

我是R新手,尝试为不同组别的分类变量(度)创建条形图。这是我与迄今使用的代码:使用ggplot2的百分比和图形标签中的条形图

graph_data <- gss %>% 
      group_by(degree, owngun) %>% 
      summarise(total = n()) %>% 
      ungroup() %>% 
      mutate(percent = total/57061)  

     ggplot(graph_data, aes(x=degree, fill=owngun, y=percent) + 
      geom_bar(stat="identity") + 
      geom_text(size = 3, position = position_stack(vjust = 0.5)) 

第一部分的作品,我能够创建一个新的变量,gunowners的百分比。然而,当我运行第二部分图表中的变量,我得到以下错误信息:

> ggplot(aes(x=degree, fill=owngun, y=percent) + 
     + geom_bar(stat="identity") 
     + ggplot(graph_data, aes(x=degree, fill=owngun, y=percent) + 
     Error: unexpected symbol in: 
     " geom_bar(stat="identity") 
     ggplot" 
     > geom_bar(stat="identity") + 
     + geom_text(size = 3, position = position_stack(vjust = 0.5)) 
     Error in position_stack(vjust = 0.5) : unused argument (vjust = 0.5) 
+1

'ggplot(aes())'中缺少一个闭括号# – beetroot

回答

1

你的语法是错误的第二部分。我已经尽最大努力纠正它,但根据您的数据集是如何定义的,这可能会或可能不会完全解决问题

ggplot(graph_data, aes(x=degree, y=percent, fill=owngun)) + geom_bar(stat="identity") + geom_text(size = 3, position = position_stack(vjust = 0.5))

要在什么是错的扩大,你定义ggplot()两次。你应该只需要这样做一次。 ggplot()为图表定义了“全局”参数。您还重复了geom_bar()两次,我不知道是否会抛出错误,但您肯定只需要一个实例。你的括号在ggplot()这两行都是错误的,你错过了第二个“)”两次,这本身就会导致图不起作用。

+0

感谢您使用您的建议,我做了一些调整,并能够使代码正常工作: – Christina

+0

@Christina根据您的评论, HenryRice帮助解决了你的问题。那么你应该考虑[当某人回答我的问题时该怎么办?](http://stackoverflow.com/help/someone-answers)。 – Uwe

0

谢谢

我用你的建议做了一些调整,并能得到的代码使用工作如下:

ggplot(graph_data, aes(x=degree, y=percent, fill=owngun, label=percent)) + 
     geom_bar(stat="identity") + 
     geom_text(size = 3, position="stack") 

剩下的唯一问题是,文本被定位在地方这使它很难阅读。我会为此努力。

+0

除了[Henry Rice]的答案(http://stackoverflow.com/a/42357529/3817004)已经解决了你的问题(根据你自己的评论),你发布你的其他SO用户还是没用的自己的答案,因为你没有提供任何数据来重现你的问题,并在你的答案最终的解决方案。 – Uwe