'ggplot x축 라벨이 너무 길 경우 폭을 고정시키고 다음줄로 넘기는 방법'에 해당되는 글 1건

  1. 2017.05.20 [R ggplot2] R ggplot 배경을 흰색으로 바꾸기, x축 라벨 각도를 90도 돌리기, x축과 y축의 위치를 바꾸기 10

R ggplot2 패키지로 box-plot 을 그렸을 때 조금 더 손을 보고 싶을 때가 있습니다.  


가령, 배경색을 흰색으로 바꾸어서 좀더 깔끔하게 보이게 하고 싶을 수 있습니다. 혹은 라벨 길이가 너무 길거가 요인 개수가 너무 많아서 가로의 X축이 모자라서 라벨명이 짤리는 상황이 발생했을 때 라벨을 45도나 90도 돌려 줌으로써 긴 라벨을 온전히 그래프에 다 제시를 해줄 수도 있겠지요. 아니면 아예 라벨을 가로축이 아니라 세로축으로 제시를 해주는 것도 방법이겠구요. 


이에 이번 포스팅에서는 아래의 3가지 소소한 팁을 공유하고자 합니다. 



(1) ggplot 배경을 흰색으로 바꾸기 


(2) ggplot x축 라벨 각도를 90도 돌리기


(3) ggplot x축과 y축 바꾸기 (x축 라벨을 세로 축으로 옮기기)

 

(4) ggplot x축 라벨의 폭(width)을 일정한 값으로 고정하고, 라벨이 일정 폭을 넘으면 다음 줄로 넘겨서 라벨을 명기하기



예제로 사용한 데이터는 MASS 패키지의 Cars93 데이터프레임에 들어있는 '차종(Type)'과 '고속도로연비(MPG.highway)' 입니다. 



> library(ggplot2)

> library(MASS)

> str(Cars93)

'data.frame': 93 obs. of  27 variables:

 $ Manufacturer      : Factor w/ 32 levels "Acura","Audi",..: 1 1 2 2 3 4 4 4 4 5 ...

 $ Model             : Factor w/ 93 levels "100","190E","240",..: 49 56 9 1 6 24 54 74 73 35 ...

 $ Type              : Factor w/ 6 levels "Compact","Large",..: 4 3 1 3 3 3 2 2 3 2 ...

 $ Min.Price         : num  12.9 29.2 25.9 30.8 23.7 14.2 19.9 22.6 26.3 33 ...

 $ Price             : num  15.9 33.9 29.1 37.7 30 15.7 20.8 23.7 26.3 34.7 ...

 $ Max.Price         : num  18.8 38.7 32.3 44.6 36.2 17.3 21.7 24.9 26.3 36.3 ...

 $ MPG.city          : int  25 18 20 19 22 22 19 16 19 16 ...

 $ MPG.highway       : int  31 25 26 26 30 31 28 25 27 25 ...

 $ AirBags           : Factor w/ 3 levels "Driver & Passenger",..: 3 1 2 1 2 2 2 2 2 2 ...

 $ DriveTrain        : Factor w/ 3 levels "4WD","Front",..: 2 2 2 2 3 2 2 3 2 2 ...

 $ Cylinders         : Factor w/ 6 levels "3","4","5","6",..: 2 4 4 4 2 2 4 4 4 5 ...

 $ EngineSize        : num  1.8 3.2 2.8 2.8 3.5 2.2 3.8 5.7 3.8 4.9 ...

 $ Horsepower        : int  140 200 172 172 208 110 170 180 170 200 ...

 $ RPM               : int  6300 5500 5500 5500 5700 5200 4800 4000 4800 4100 ...

 $ Rev.per.mile      : int  2890 2335 2280 2535 2545 2565 1570 1320 1690 1510 ...

 $ Man.trans.avail   : Factor w/ 2 levels "No","Yes": 2 2 2 2 2 1 1 1 1 1 ...

 $ Fuel.tank.capacity: num  13.2 18 16.9 21.1 21.1 16.4 18 23 18.8 18 ...

 $ Passengers        : int  5 5 5 6 4 6 6 6 5 6 ...

 $ Length            : int  177 195 180 193 186 189 200 216 198 206 ...

 $ Wheelbase         : int  102 115 102 106 109 105 111 116 108 114 ...

 $ Width             : int  68 71 67 70 69 69 74 78 73 73 ...

 $ Turn.circle       : int  37 38 37 37 39 41 42 45 41 43 ...

 $ Rear.seat.room    : num  26.5 30 28 31 27 28 30.5 30.5 26.5 35 ...

 $ Luggage.room      : int  11 15 14 17 13 16 17 21 14 18 ...

 $ Weight            : int  2705 3560 3375 3405 3640 2880 3470 4105 3495 3620 ...

 $ Origin            : Factor w/ 2 levels "USA","non-USA": 2 2 2 2 2 1 1 1 1 1 ...

 $ Make              : Factor w/ 93 levels "Acura Integra",..: 1 2 4 3 5 6 7 9 8 10 ...

 




  (1) ggplot 그래프 배경을 흰색으로 바꾸기 : theme_bw() 


기본 설정값을 사용해서 박스 그래프를 그려보면 아래와 같은 배경색으로 그래프가 나타납니다. 



# box-plot by default

ggplot(Cars93, aes(x=Type, y=MPG.highway)) +

  geom_boxplot()

 






ggplot배경을 흰색으로 바꾸려면 theme_bw() 를 추가해주면 됩니다. 


 

# box-plot with white background

ggplot(Cars93, aes(x=Type, y=MPG.highway)) +

  geom_boxplot() +

  theme_bw() # white background 






 (2) ggplot x축 라벨 각도를 90도 돌리기 : theme(axis.text.x=element_text(angle=90, hjust=1))


이번에는 x축에 있는 '차종(Type)' 라벨을 90도 회전시켜서 세로로 세워보겠습니다.  

라벨이 길다거나 라벨 개수가 많아서 x축에 다 안들어가는 바람에 라벨이 짤리는 경우에 사용하면 유용합니다. 



# box-plot with axis label's angle of 90 degrees

ggplot(Cars93, aes(x=Type, y=MPG.highway)) +

  geom_boxplot() +

  theme_bw() +

  theme(axis.text.x=element_text(angle=90, hjust=1))




 




물론 라벨을 눕히는 각도를 'angle' 옵션을 사용해서 원하는 만큼 조절할 수도 있습니다.  

아래는 x축 라벨의 각도를 45도 회전시켜본 예제입니다. 



# box-plot with x axis label's angle of 45 degrees

ggplot(Cars93, aes(x=Type, y=MPG.highway)) +

  geom_boxplot() +

  theme_bw() +

  theme(axis.text.x=element_text(angle=45, hjust=1))


 





x축 라벨을 회전시킬 수 있으면 y축 라벨도 회전시킬 수 있겠지요? 

아래 예제는 왼쪽 세로의 y축 라벨을 45도 회전 시켜본 것입니다. 



# box-plot with y axis label's angle of 45 degrees

ggplot(Cars93, aes(x=Type, y=MPG.highway)) +

  geom_boxplot() +

  theme_bw() +

  theme(axis.text.y=element_text(angle=45, hjust=1))


 






 (3) ggplot x축과 y축의 위치를 바꾸기 : coord_flip()


아래는 coord_flip() 을 사용해서 x축의 '차종(Type)'을 세로축으로 옮기고, y축의 '고속도로연비(MPG.highway)'를 가로축으로 옮겨본 것입니다. 


x축의 라벨이 너무 많거나 길 경우에 이처럼 x축과 y축을 바꿔주면 라벨이 짤리는 경우 없이 세로로 길게 볼 수 있어서 유용합니다. 



# box-plot with the label at vertical axis

ggplot(Cars93, aes(x=Type, y=MPG.highway)) +

  geom_boxplot() +

  theme_bw() +

  coord_flip()





 

 

  (4) ggplot x축 라벨의 폭(width)을 일정한 값으로 고정하고, 
     라벨이 일정 폭을 넘으면 다음 줄로 넘겨서 라벨을 명기하기

   : aes(stringr::str_wrap(V1, 15), V2)

 

x 축 라벨이 너무 많거나 길 경우에 위의 (3번) x축, y축 바꾸기 외에도, 이번에 소개할 x축의 폭(width)을 stringr::str_wrap() 함수일정한 값으로 고정하고, 그 갑을 넘으면 다음 줄로 넘겨서 라벨을 표시하도록 하는 방법이 있습니다.  아래에 간단한 예를 들어서 전, 후 비교 설명을 해보겠습니다.

 

  • x축의 라벨이 너무 많고 길어서 서로 중첩되고 있는 예제

 

> library(ggplot2)
> library(MASS)
> library(stringr)
> 
> label <- c("1_Short", 
+            "2_Long label", 
+            "3_A very, very long label", 
+            "4_Really long, long, long and long label",
+            "5_An extremely long, long, long, and long label")
> value <- c(10, 20, 30, 40, 50)
> df <- data.frame(label, value)
> 
> ggplot(df, aes(x=label, y=value)) +
+   geom_bar(stat="identity") + 
+   xlab(NULL)

 

 

 

 

  • x축의 라벨 폭(width)을 stringr 의 str_wrap() 함수로 폭을 조정한 예제

 

> ggplot(df, aes(x=label, y=value)) + + geom_bar(stat="identity") + + aes(stringr::str_wrap(label, 15), value) + + xlab(NULL)

 

 

 


 

많은 도움이 되었기를 바랍니다. 


이번 포스팅이 도움이 되셨다면 아래의 '공감~'를 꾹 눌러주세요. ^^





728x90
반응형
Posted by Rfriend
,