coord_flip()
>?coord_flip
When assigning manufacturer variable of mpg to x-axis, It is hard to seize the name of elements of manufacturer variable.
Because 'manufacturer' in 'mpg' tend to be overlapped having a long elements such as 'volkswagen','toyota'.
So we need to flip the columns to horizontal so that elements are not overlapped.
<EXAMPLE1>
> manufacturer_class<-mpg%>%count(manufacturer,class)%>%group_by(manufacturer)%>%mutate(ratio=n/sum(n)*100)
> manufacturer_class
# A tibble: 32 x 4
# Groups: manufacturer [15]
manufacturer class n ratio
<chr> <chr> <int> <dbl>
1 audi compact 15 83.3
2 audi midsize 3 16.7
3 chevrolet 2seater 5 26.3
4 chevrolet midsize 5 26.3
5 chevrolet suv 9 47.4
6 dodge minivan 11 29.7
7 dodge pickup 19 51.4
8 dodge suv 7 18.9
9 ford pickup 7 28.
10 ford subcompact 9 36
# ... with 22 more rows
> ggplot(data=manufacturer_class,aes(x=manufacturer,y=ratio,fill=class))+geom_col()
> ggplot(data=manufacturer_class,aes(x=manufacturer,y=ratio, fill=class))+geom_col()+coord_flip()
> manufacturer_class_2<-mpg%>%filter(class==c("compact","suv"))%>%count(manufacturer,class)
%>%group_by(manufacturer)%>%mutate(ratio=n/sum(n)*100)
> ggplot(data=manufacturer_class_2,aes(x=manufacturer,y=ratio,fill=class))+geom_col()
> ggplot(data=manufacturer_class_2,aes(x=manufacturer,y=ratio,fill=class))+geom_col()+coord_flip()
<EXAMPLE2>
> mpg$yearr<-ifelse(mpg$year=1999,"old","new"))
> mpg<-mpg%>%count(manufacturer,yearr)%>%group_by(manufacturer)%>%mutate(rate_year=n/sum(n)*100)
> ggplot(data=mpg,aes(x=manufacturer,y=rate_year,fill=yearr))+geom_col()
> ggplot(data=mpg,aes(x=manufacturer,y=rate_year,fill=yearr))+geom_col()+coord_flip()
> ggplot(data=mpg,aes(x=manufacturer,y=rate_year,fill=yearr))+geom_col(position="dodge")+coord_flip()
[R] - (R) Fill,Color columns based on a variable/aes(x=,y=,fill=)/geom_col(position="dodge")
'R' 카테고리의 다른 글
(R) list colors of columns in order / character type to factor type (0) | 2020.07.30 |
---|---|
(R) Reorder columns in any orders / scale_x_discrete() (0) | 2020.07.30 |
(R) count the number of elements/ count() (0) | 2020.07.29 |
(R)Make a new variable/ mutate() (0) | 2020.07.27 |
(R) [dplyr] Rearrange data in order / arrange() / arrange(desc()) (0) | 2020.07.26 |