R-Studio barplot, plot 그리기.

R-Studio의 세로막대, 꺾은선 차트 그리기.

Featured image

R-Studio 도 함수를 만들 수 있다.

차트를 그리기에 앞서 차트를 그릴 인자 값의 자료형이 행렬 혹은 벡터 여야 한다.
본래 차트 함수에 legend 인자가 있는경우 legend() 함수의 단독 함수 사용이 대부분 가능하다.

사용된 함수

Use Descriptions
plot(x...) 꺾은선 그래프
barplot(x...) 세로막대 그래프

파일 소스

우클릭 -> 다른이름으로 링크저장 이용해 주세요
2013년_서울_주요구별_병원현황.csv

사용 예시 소스코드

# library(dplyr)
  # library(plotrix)
  
  getColorValue <- function(vec) {
    
    return(rainbow(length(vec)))
  }
  
  # 데이터 불러오기
  myCsv <- read.csv("2013년_서울_주요구별_병원현황.csv")
  myCsv
  str(myCsv)
  
  # 범례 뽑기, x축 제목 뽑기
  bum <- myCsv$표시과목
  base_Val <- myCsv[-1]
  
  # 수치 메트릭스화
  exam01 <- as.matrix(base_Val)
  exam01
  
  # 색 뽑기
  myCol01 <- getColorValue(bum)
  
  # 차트 그리기기
  barplot(exam01, beside = T, col = myCol01, ylim = c(0, 350), main = "서울시 주요 구별 과목별 병원현황 - 2013년 출처[국민건강보험공단]")
  abline(h=seq(0, 350, 10), lty=3, lwd=1)
  legend(x="topright", legend = bum, bty = "o", fill = myCol01, col = myCol01)
  ###############################################################################
  
  # 강서구 구로구 그리기
  # 수치 메트릭스화
  exam02 <- as.matrix(base_Val[c("강서구", "구로구")])
  exam02
  barplot(exam02, beside = T, col = myCol01, ylim = c(0, 50), xlab="지역 구분", ylab="이용 고객수", main = "강서구 구로구 병원 현황")
  legend(x="topright", legend = bum, lty=1, col = myCol01, cex = 0.7)
  ###############################################################################
  
  # 마포구 병원 현황 비율
  exam03 <- as.matrix(base_Val["마포구"])
  exam03
  
  pie_3D <- pie3D(exam03, main = "마포구 병원 현황 비율")
  pec01 <- paste(bum, "\n", round(exam03/sum(exam03)*100, 2), "%")
  pie3D.labels(pie_3D, labels = pec01, labelcex = 0.8)
  ###############################################################################
  
  # 차트 for문 돌리기
  len <- length(base_Val)
  par(mfrow=c(2, len/2)) # 2행 len열짜리 공간 만듬
  for(idx in seq(1, len, 1)) {
    temp <- as.matrix(base_Val[idx]) #1 컬럼씩 가져옴
    barplot(as.vector(temp), beside = T, col = myCol01, ylab="병원수", xlab="", main = colnames(temp))
  }
  
  # 연령별 꺾은 선 그래프
  par(mfrow=c(1, 1))
  base_Age <- myCsv %>% filter(표시과목=="정형외과" | 표시과목=="안과" | 표시과목=="피부과") %>% select(표시과목, 강동구, 동대문구, 동작구, 마포구, 서대문구)
  base_Age #필터
  
  
  bum01 <- colnames(base_Age[-1])
  xVal <- as.matrix(base_Age[-1])
  row <- nrow(xVal)
  len <- length(bum01)
  xLabels <- as.matrix(base_Age["표시과목"])
  myCol02 <- rainbow(len-1)
  
  # for문으로 꺾은선 그리기
  plot(xVal[1:row, 1], xlab="", ylab="", main="연령별 꺾은 선 그래프", type='o', col="violet", lwd=2, axes=F, ylim = c(0, 30))
  
  for(idx in seq(2, len, 1)) {
    age <- xVal[1:3, idx]
    lines(age, col=myCol02[idx-1], type='o', lwd=2)
  }
  
  # x축(1) y축(2)
  # las : x레이블 방향 1:가로, 2:세로
  axis(side=1, at=1:row,  labels = xLabels, las=2)
  axis(side=2, las = 1)
  # 수평 수직 눈금 그리기
  abline(h=seq(0, 30, 5), lty=2, lwd=0.2)
  
  colors <- c('violet', myCol02)
  
  legend('topright', bum01, cex=0.8, 
         col=colors, lty=1, lwd=2, bg='white')