본문 바로가기
R

(R) Reorder columns in any orders / scale_x_discrete()

by jangpiano 2020. 7. 30.
반응형

scale_x_discrete()


>library(ggplot2)   ------------for 'airquality' data 

>library(dplyr)

> summary(airquality$Ozone)

   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 

   1.00   18.00   31.50   42.13   63.25  168.00      37 

> summary(airquality$Temp)

   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 

  56.00   72.00   79.00   77.88   85.00   97.00 

> airquality_<-airquality%>%filter(!is.na(Ozone))%>%mutate(Ozone_rank=ifelse(Ozone<=31.50,"little",ifelse(Ozone<=63.25,"middle","much")))%>%mutate(temp_rank=ifelse(Temp<=72,"warm",ifelse(Temp<=85,"hot","very hot")))

> table(airquality_$Ozone_rank)

   little middle   much 

     58     29     29 

> table(airquality_$temp_rank)

     hot very hot     warm 

      56       27       33 

> Ozone_temp<-airquality_%>%group_by(Ozone_rank)%>%summarise(mean_temp=mean(Temp))

> ggplot(data=Ozone_temp,aes(x=Ozone_rank,y=mean_temp))+geom_col()

> ggplot(data=Ozone_temp,aes(x=Ozone_rank,y=mean_temp))+geom_col()+scale_x_discrete(limits=c("much","middle","little"))

<application>

> Ozone_temp_rate<-airquality_%>%count(Ozone_rank,temp_rank)%>%group_by(Ozone_rank)%>%mutate(per=n/sum(n)*100)

> Ozone_temp_rate$temp_order<-factor(Ozone_temp_rate$temp_rank, level=c("warm","hot","very hot")

> ggplot(data=Ozone_temp_rate,aes(x=Ozone_rank,y=per,fill=temp_order))+geom_col()

> ggplot(data=Ozone_temp_rate,aes(x=Ozone_rank,y=per,fill=temp_order))+geom_col()+scale_x_discrete(limits=c("much","middle","little"))


반응형