본문 바로가기
R

(R) The way to make bar_graph having both x and y/geom_bar(stat="identity)

by jangpiano 2020. 8. 13.
반응형

<geom_bar(stat="identity")>


When using bar graph, you cannot have both variable x and y in the graph. 


> ggplot(data=msleep2,aes(x=vore,y=mean_sleep))+geom_bar()

Error: stat_count() can only have an x or y aesthetic.



Generally, y-axis of bar graph automatically becomes 'counts'. You can make the bar_graph having variables for x-axis and y-axis by using geom_bar(stat="identity)



variable x and count  - geom_bar() 

 variable x and y  - geom_bar(stat="identity")

>library(ggplot2)

> ggplot(data=msleep,aes(x=vore))+geom_bar()

>library(ggplot2)

>library(dplyr)

>msleep2<-msleep%>%group_by(vore)%>%summarise(mean_sleep=mean(sleep_total))

> ggplot(data=msleep2,aes(x=vore,y=mean_sleep))+geom_bar(stat="identity")

 

 


<geom_bar(stat="identity") VS geom_col()>



geom_bar(stat="identity")  

 geom_col()

 >ggplot(data=msleep2,aes(x=vore,y=mean_sleep))+geom_bar(stat="identity")

 >ggplot(data=msleep2,aes(x=vore,y=mean_sleep))+geom_col()

 

when the variable x is numeric. 


> str(mpg$cyl)

 int [1:234] 4 4 4 4 6 6 6 4 4 4 ...


> table(mpg$cyl)


 4  5  6  8 

81  4 79 70 


> cyl_hwy<-mpg%>%group_by(cyl)%>%summarise(mean_hwy=mean(hwy))


> ggplot(data=cyl_hwy,aes(x=cyl,y=mean_hwy))+geom_bar(stat="identity")



> ggplot(data=cyl_hwy,aes(x=factor(cyl),y=mean_hwy))+geom_bar(stat="identity")

 when the variable x is numeric. 


> str(mpg$cyl)

 int [1:234] 4 4 4 4 6 6 6 4 4 4 ...


> table(mpg$cyl)


 4  5  6  8 

81  4 79 70 


>cyl_hwy<-mpg%>%group_by(cyl)%>%summarise(mean_hwy=mean(hwy))


> ggplot(data=cyl_hwy,aes(x=cyl,y=mean_hwy))+geom_col()


> ggplot(data=cyl_hwy,aes(x=factor(cyl),y=mean_hwy))+geom_col()










반응형