채니의 개발일기

ggplot 사용하기 본문

프로그래밍언어/R기초

ggplot 사용하기

윤채니챈 2023. 6. 17. 17:46
728x90
반응형

- 사용할 데이터(캐글데이터 사용)

https://www.kaggle.com/datasets/nehalbirla/vehicle-dataset-from-cardekho

 

Vehicle dataset

Used Cars data form websites

www.kaggle.com

 

0. 데이터 로드하기

dir = '/Users/yunchaewon/Desktop/r-data analysis/'
usedcar = read.csv(paste0(dir,'car data.csv'),stringsAsFactors = FALSE)
str(usedcar)

- 데이터 상태확인

'data.frame':	301 obs. of  9 variables:
 $ Car_Name     : chr  "ritz" "sx4" "ciaz" "wagon r" ...
 $ Year         : int  2014 2013 2017 2011 2014 2018 2015 2015 2016 2015 ...
 $ Selling_Price: num  3.35 4.75 7.25 2.85 4.6 9.25 6.75 6.5 8.75 7.45 ...
 $ Present_Price: num  5.59 9.54 9.85 4.15 6.87 9.83 8.12 8.61 8.89 8.92 ...
 $ Kms_Driven   : int  27000 43000 6900 5200 42450 2071 18796 33429 20273 42367 ...
 $ Fuel_Type    : chr  "Petrol" "Diesel" "Petrol" "Petrol" ...
 $ Seller_Type  : chr  "Dealer" "Dealer" "Dealer" "Dealer" ...
 $ Transmission : chr  "Manual" "Manual" "Manual" "Manual" ...
 $ Owner        : int  0 0 0 0 0 0 0 0 0 0 ...

1. ggplot()로드하고 도화지준비

library(ggplot2)
ggplot()

 

2. 축그리기 : aes()

ggplot(usedcar,aes(x= Year))

 

 

ggplot(데이터,aex(x =x축으로 사용할 변수값)

 

aes(x=Year): Year 변수의 값을 x축으로 사용하여 데이터를 시각화

 

 

 

 

 

3. 그래프그리기 :geom_bar()

geom_bar() 함수 : 주어진 데이터를 기반으로 막대 그래프를 그리는 역할

 

ggplot(usedcar,aes(x= Year))+
  geom_bar()

 

 

 

 

 

 

4.그래프 배경 수정: theme_classic()

theme_classic(): 그래프의 외관을 클래식한 스타일로 변경가능

ggplot(usedcar,aes(x=Year))+
  geom_bar()+
  theme_classic()

 

 

 

 

5. 글씨체 변경

1. theme() 함수: 그래프의 다양한 요소들을 조정할 수 있는 매개변수를 제공.

이 함수를 사용하여 그래프의 배경, 축, 눈금선, 제목 등의 요소를 변경할 수 있다.

2.element_text() 함수: theme() 함수 내에서 텍스트 요소를 조정하는 데 사용되는 함수. element_text() 함수를 사용하여 텍스트의 크기(size), face(굵기)(bold, italic), 색상(color), 폰트(family) 등을 설정

ggplot(usedcar,aes(x=Year))+
  geom_bar()+
  theme_classic()+
  theme(text = element_text(size=15,face='bold'))

 

6. 그래프 축간격 조정 : scale_x_continuousscale_y_continuous 사용

 

ggplot(usedcar,aes(x=Year))+
  geom_bar()+
  theme_classic()+
  theme(text = element_text(size=15,face='bold'))+
  scale_x_continuous(breaks = seq(2002,2020,by=2))+
  scale_y_continuous(breaks = seq(0,60,by=10))+

 

 

 

 

7. 그래프 색 입히기 : fill 매개변수를 사용하여 각 막대의 색

 

ggplot(usedcar,aes(x=Year))+
  geom_bar(aes(fill = Transmission))+
  theme(text = element_text(size=15,face='bold'),
        legend.position = 'top')+
  scale_x_continuous(breaks = seq(2002,2020,by=2))+
  scale_y_continuous(breaks = seq(0,60,by=10))

legend.position을 활용하여 범례(Transmission표시) 위치를 변경가능

aesggplot() 함수의 인자로 사용되어 그래프 객체를 생성할 때 시각적 속성을 정의한다. 데이터 프레임을 지정하고 aes를 사용하여 x축, y축, 색상 등을 설정할수 있다. 

 

 


theme_bw(): 래프의 배경을 흰색으로 설정하고, 축 라인과 눈금의 색상을 검은색으로 설정하는 테마

 

1. theme_bw()적용안한 그래프 

2.theme_bw()적용한 그래프

728x90
반응형