- 두개의 변수간 관계를 확인할 때 유용한 그래프 - 이상치를 탐지하기 좋음 (선형관계/ 비선형관계/ 양의 상관관계/ 음의 상관관계/ 상관관계가 없음)
문법1. 중고차 데이터의 x 축을 주행거리로 하고 y축을 가격으로 해서 산포도 그래프 를 plotly 로 그리시오 !
# 데이터 불러오기
library(plotly)
setwd("c:\\data")
usedcars <- read.csv("usedcars.csv", header=TRUE)
# 산포도 그래프 생성
fig <- plot_ly( data= usedcars,
x = ~mileage,
y = ~price,
type='scatter',
mode='markers',
marker = list(color='blue'))
# 그래프 출력
fig
시설명: 주행거리가 높을 수록 중고차가격이 하락하는 패턴을 보입니다.
문법 2. 위 그래프에 추세선을 추가하시오.
# 데이터 불러오기
library(plotly)
setwd("c:\\data")
usedcars <- read.csv("usedcars.csv", header=TRUE)
# 산포도 그래프 생성
fig <- plot_ly( data= usedcars,
x = ~mileage,
y = ~price,
type='scatter',
mode='markers',
marker = list(color='blue'))
# 추세선 추가
fig <- fig%>%add_trace(x=usedcars$mileage,
y=fitted(lm(price~mileage, data=usedcars)),
type='scatter',
mode='lines',
line=list(color='red'),
name='Trend Line')
# 그래프 출력
fig
※ 명령어1 %> % 명령어2
-> %>%(파이프) 라는 용어로 불리고 명령어1의 결과를 명령어 2의 입력값으로 보내겠다는 뜻. ※ fig %>% and add_trace -> fig 객체의 새로운 트레이스를 추가하는 코드 (기존 그래프를 추가하겠다는 것) ※ y=fitter(lm(price~mileage, data=usedcars)) -> y 축 데이터로 price 와 milege 간의 선형 회귀모델을 만들어서 예측값을 y 축 데이터 값으로 사용합니다. -> price 가 종속변수이가 milege 가 독립변수 입니다. fitted 는 회귀 예측값을 y 축 좌표로 사용하겠다는것입니다.
문제1. x축을 연식으로 하고 y축을 가격으로 해서 산포도 그래프를 구하시오. (추세선 포함)
# 데이터 불러오기
library(plotly)
setwd("c:\\data")
usedcars <- read.csv("usedcars.csv", header=TRUE)
# 산포도 그래프 생성
fig <- plot_ly( data= usedcars,
x = ~year,
y = ~price,
type='scatter',
mode='markers',
marker = list(color='blue'))
# 추세선 추가
fig <- fig%>%add_trace(x=usedcars$year,
y=fitted(lm(price~year, data=usedcars)),
type='scatter',
mode='lines',
line=list(color='red'),
name='Trend Line')
# 그래프 출력
fig
문법3. 자동화 코드를 편하게 사용할 수 있도록 메시지가 화면에 출력되게하시오. (yys.R 스크립트 저장)
# 필요한 패키지 로드
library(svDialogs) # 대화형 사용자 인터페이스 화면을 출력하게 해주는 패키지
# 옵션 메시지 정의
options_message <- "1: 막대 그래프 코드\n2: 원형 그래프 코드\n\n번호를 선택하세요:"
# 사용자 입력 받기 (대화 상자 사용)
dialog_result <- dlgInput(message = options_message, "")$res
num <- as.integer(dialog_result)
# switch 문을 사용해서 선택에 따라 다른 메세지 출력
result <- switch(as.character(num),
"1" = cat(readLines("bar_plot.R"), sep = "\n"),
"2" = cat(readLines("pie_plot.R"), sep = "\n"),
"유효하지 않은 선택입니다."
)
cat(result, "\n")
문법 4. 자동화 스크립트를 수행했을 때 그래프와 관련된 코드도 나오지만 그 그래프도 바로 출력되게 하시오. (yys.R 코드 수정)
# 필요한 패키지 로드
library(svDialogs)
library(plotly)
# 옵션 메시지 정의
options_list <- list("1: 막대 그래프 코드", "2: 원형 그래프 코드")
# 사용자 입력 받기 (대화 상자 사용)
dialog_result <- dlgList(options_list, title = "번호를 선택하세요")$res
# switch 문을 사용해서 선택에 따라 다른 메세지 출력 및 실행
if (is.null(dialog_result)) {
cat("유효하지 않은 선택입니다.\n")
} else {
num <- as.integer(substr(dialog_result, 1, 1)) # 선택한 옵션의 첫 글자를 숫자로 변환
fig <- switch(as.character(num),
"1" = {
cat(readLines("bar_plot.R"), sep = "\n")
source("bar_plot.R", local = TRUE)
fig # bar_plot.R에서 생성된 fig 객체 반환
},
"2" = {
cat(readLines("pie_plot.R"), sep = "\n")
source("pie_plot.R", local = TRUE)
fig # pie_plot.R에서 생성된 fig 객체 반환
},
{
cat("유효하지 않은 선택입니다.\n")
NULL
}
)
if (!is.null(fig)) {
print(fig) # fig 객체를 명시적으로 출력
}
}