본문 바로가기
R

R reorder() -reorder columns in ascending order, descending order when setting aes()

by jangpiano 2020. 7. 21.
반응형

Reorder Columns


<How to make columns in R>

1. make summary (using dplyr)

2. decide x-axis, y-axis

3. draw columns (using ggplot2)


<How to make reordered columns in R>

During step3, you should use reorder() function in x-axis

<How to make columns in R>



1. Make Summary 



> library(ggplot2)

> library(dplyr)

drv_cty<-mpg%>%group_by(drv)%>%summarise(mean_cty=mean(cty))

drv_cty

# A tibble: 3 x 2

drv   mean_cty

<chr>    <dbll>

1 4         14.3

2 f         20.0

3 r         14.1


2. Decide X,Y axis


x-axis: drv

Y-axis: mean_cty




3. Draws columns


> ggplot(data=drv_cty, aes(x=drv, y=mean_cty))+geom_col()



<How to make reordered columns in R>

STEP 1,2 is same with <How to make columns in R>

3. Draw Reordered Columns

1. Reorder X-axis in ascending order

> ggplot(data=drv_cty,aes(x=reorder(drv,mean_cty),y=mean_cty))+geom_col()



2. Reorder X-axis in descending order


> ggplot(data=drv_cty,aes(x=reorder(drv,-mean_cty),y=mean_cty))+geom_col()







   


반응형