ggplot不使用geom_bar

时间:2017-03-16 06:49:47

标签: r ggplot2 bar-chart geom-bar

您好我想弄清楚这两组代码之间的差异,即使两者都相同,也会给出不同的图。如果代码2中有任何错误,请帮助我。代码2没有像代码1那样给出确切的图。

代码1:

por %>%  
  group_by(sex,romantic) %>% 
   summarise(n=mean(G3,na.rm=T)) %>% 
    ggplot(aes(x=sex, y=n, fill=romantic)) +    
     geom_bar(position="dodge",stat="identity") +   
      ggtitle("Romantic Relationship, Grades and Gender")

Plot 1

代码2:

q <-summarise(por,n=mean(G3,na.rm=T)) 

ggplot(por, aes(sex, as.numeric(q), fill = romantic)) +    
  geom_bar(position="dodge",stat="identity") +
    ggtitle("Romantic Relationship,Grades and Gender")

Plot 2

----这里是Object的结构:---

str(por) 'data.frame':  649 obs. of  6 variables:   
  $ sex       : chr   "F" "F" "F" "F" ...    
  $ age       : int  18 17 15 15 16 16 16 17 15 15...   
  $ romantic  : chr  "no" "no" "no" "yes" ...    
  $ G1        : int  0 9 12 14 11 12 13 10 15 12 ...    
  $ G2        : int  11 11 13 14 13 12 12 13 16 12 ...    
  $ G3        : int  11 11 12 14 13 13 13 13 17 13 ...

1 个答案:

答案 0 :(得分:0)

在你的第一个代码中: 总结是通过分组&#34;性别&#34;和#34;浪漫&#34;,它给你不同的观察n

在你的第二个代码中: 正在为&#34; G3&#34;的所有值进行总结,为您留下一个单一的n值

试试这个:

q <-por %>% group_by(sex,romantic) %>% 
  summarise(n=mean(G3,na.rm=T))

此外,它需要与por

结合使用
por<-merge(por,q,by=c("sex","romantic")
相关问题