■ 산포도 그래프와 상관관계
"산포도 그래프를 데이터간의 상관 관계를 나타낼 때 유용하다"
예제: 나이와 소득간의 상관관계가 있는지 데이터를 시각화 하시오
age_income<-read.csv("emp_class.csv", header=T)
head(age_income)
plot(age_income$age, age_income$month_income,
col="red",
xlab="나이",
ylab="소득",
pch=16)
아래의 산포도 그래프를 보면 나이, 소득이 상관있어 보이는데
그럼 상관관계가 얼마나 되는지 확인하려면
cor 함수를 사용하면 됩니다.
cor(age_income$age, age_income$month_income)
[1] 0.8553024
※ 소수 숫자 설명
0.0~0.2 상관관계가 거의 없다.
0.2~0.4 상관관계가 낮다.
0.4~0.6 상관관계가 있다.
0.6~0.8 상관관계가 높다.
0.8~1.0 상관관계가 매우 높다.
문제142.
plotly 패키지를 이용해서 나이, 소득의 산포도 그래프를 그리시오
library(plotly)
plot_ly(data = age_income,
x = ~age_income[,"age"],
y = ~age_income[,"month_income"],
type="scatter",
mode="dot")
*markers로 바꾸면 다른거 나옴
구글에다가
#130177
쓰면 컬러 조절 나옴
library(plotly)
#아래 그래프 실행시킬때마다 라이브러리 해줘야 함
plot_ly(data = age_income,
x = ~age_income[,"age"],
y = ~age_income[,"month_income"],
type="scatter",
mode="markers",
color=I('#a80682') )
*잘 안보이지만 싱글쿼테이션 있음 ㅋ
문제143.
샤이니의 사이드 메뉴 아래쪽에 Plotchart 를 추가해서
x축과 y축을 입력받아 산포도 그래프가 출력되게 하시오
그래프 아래쪽에 상관계수도 같이 출력되게 하시오!
############## set this file location to working directory
##########################
packages <- 'rstudioapi'
if (length(setdiff(packages, rownames(installed.packages()))) > 0) {
install.packages(setdiff(packages, rownames(installed.packages())))
}
library('rstudioapi')
current_dir<-dirname(rstudioapi::getSourceEditorContext()$path)
setwd(current_dir)
package_in<-function(p_name,option=1){
packages <- p_name
if (length(setdiff(packages, rownames(installed.packages()))) > 0) {
install.packages(setdiff(packages, rownames(installed.packages())))
}
if (option==1){
library(p_name,character.only = TRUE)
}
}
###########################1. 패키지
설치##########################################
package_in('shinydashboard')
package_in('shiny')
package_in('ggplot2')
package_in('plotly')
######################### 2. 화면 개발
###########################################
sidebar <- dashboardSidebar(
sidebarMenu(
fileInput("file1", "Choose CSV File",
multiple = FALSE,
accept = c("text/csv",".xlsx",".txt",
"text/comma-separated-values,text/plain",
".csv")),
menuItem("Plot",
menuSubItem('Barplot',tabName='barplot'),
menuSubItem('Piechart',tabName='piechart'),
menuSubItem('Linechart',tabName='linechart'),
menuSubItem('Plotly',tabName='plotly')
)
)
)
body <- dashboardBody(
tabItems(
##### bar plot
tabItem(tabName = "barplot",
sidebarPanel(
selectInput("in_sel_bar_xVar","x Variable:", choices = NULL),
selectInput("in_sel_bar_yVar","y Variable:", choices = NULL)
),
mainPanel(
plotOutput('plot_bar')
)
),
##### piechart
tabItem(tabName = "piechart",
sidebarPanel(
selectInput("in_sel_pie_xVar","x Variable:", choices = NULL)
),
mainPanel(
plotlyOutput('plot_pie')
)
),
##### linechart
tabItem(tabName = "linechart",
sidebarPanel(
selectInput("in_sel_line_xVar","x Variable:", choices = NULL),
selectInput("in_sel_line_yVar","Y Variable:", choices = NULL)
),
mainPanel(
plotlyOutput('plot_line')
)
),
##### plotly
tabItem(tabName = "plotly",
sidebarPanel(
selectInput("in_sel_plotly_xVar","x Variable:", choices = NULL),
selectInput("in_sel_plotly_yVar","Y Variable:", choices = NULL)
),
mainPanel(
plotlyOutput('plot_ly')
)
)
)
)
ui<-dashboardPage(
dashboardHeader(title='my graph'),
sidebar,
body
)
######################3. 서버단 개발 ########################################
server <- function(input, output,session) {
options(warn = -1)
options(shiny.maxRequestSize = 30*1024^2)
dataload<-reactive({
req(input$file1)
file1 = input$file1
data1 = read.csv(file1$datapath)
updateSelectInput(session, "in_sel_bar_xVar", choices = colnames(data1))
updateSelectInput(session, "in_sel_bar_yVar", choices = colnames(data1))
updateSelectInput(session, "in_sel_pie_xVar", choices = data1[,1])
updateSelectInput(session, "in_sel_line_xVar", choices = colnames(data1))
updateSelectInput(session, "in_sel_line_yVar", choices = colnames(data1))
updateSelectInput(session, "in_sel_plotly_xVar", choices = colnames(data1))
updateSelectInput(session, "in_sel_plotly_yVar", choices = colnames(data1))
return(data1)
})
####nomal_bar
output$plot_bar <- renderPlot({
table_in<-dataload()
xdata<-as.factor(table_in[,input$in_sel_bar_xVar])
ydata<-as.factor(table_in[,input$in_sel_bar_yVar])
fdata=data.frame(x=xdata,y=ydata)
ggplot(fdata) +
geom_bar(aes_string(x='x',y='y',fill='x'),stat =
"identity",show.legend=F)
})
output$plot_pie <- renderPlotly({
table_in<-dataload()
plot_ly(table_in, labels = ~colnames(table_in)[-1], values=~as.factor(
table_in[table_in[,1] == input$in_sel_pie_xVar,-1] ),type='pie')
})
output$plot_line <- renderPlotly({
table_in<-dataload()
#라벨 명 지정
x <- list(title = input$in_sel_line_xVar)
y <- list(title = input$in_sel_line_yVar)
plot_ly(data = table_in,
x=~table_in[,input$in_sel_line_xVar],
y=~table_in[,input$in_sel_line_yVar],
type='scatter',mode='dot')%>%
layout(xaxis = x, yaxis = y)
})
output$plot_ly <- renderPlotly({
table_in<-dataload()
#라벨 명 지정
x <- list(title = input$in_sel_plotly_xVar)
y <- list(title = input$in_sel_plotly_yVar)
plot_ly(data = table_in,
x = ~table_in[,input$in_sel_plotlyt_xVar],
y = ~table_in[,input$in_sel_plotly_yVar],
type="scatter",
mode="markers",
color=I('#a80682') )
})
}
######################### 4. 샤이니 실행 ###############################
shinyApp(ui = ui, server = server)
▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
##################레티스 넣은 코드#############################
############## set this file location to working directory ##########################
packages <- 'rstudioapi'
if (length(setdiff(packages, rownames(installed.packages()))) > 0) {
install.packages(setdiff(packages, rownames(installed.packages())))
}
library('rstudioapi')
current_dir<-dirname(rstudioapi::getSourceEditorContext()$path)
setwd(current_dir)
package_in<-function(p_name,option=1){
packages <- p_name
if (length(setdiff(packages, rownames(installed.packages()))) > 0) {
install.packages(setdiff(packages, rownames(installed.packages())))
}
if (option==1){
library(p_name,character.only = TRUE)
}
}
###########################1. 패키지 설치##########################################
package_in('shinydashboard')
package_in('shiny')
package_in('ggplot2')
package_in('plotly')
package_in('lattice')
######################### 2. 화면 개발 ###########################################
sidebar <- dashboardSidebar(
sidebarMenu(
fileInput("file1", "Choose CSV File",
multiple = FALSE,
accept = c("text/csv",".xlsx",".txt",
"text/comma-separated-values,text/plain",
".csv")),
menuItem("Plot",
menuSubItem('Barplot',tabName='barplot'),
menuSubItem('Piechart',tabName='piechart'),
menuSubItem('Lineplot',tabName='lineplot'),
menuSubItem('Scatterplot',tabName='scatterplot')
)
)
)
body <- dashboardBody(
tabItems(
##### bar plot
tabItem(tabName = "barplot",
sidebarPanel(
selectInput("in_sel_bar_yVar","y Variable:", choices = NULL),
selectInput("in_sel_bar_xVar","x Variable:", choices = NULL)
),
mainPanel(
plotOutput('plot_bar')
)
),
##### piechart
tabItem(tabName = "piechart",
sidebarPanel(
selectInput("in_sel_pie_xVar","x Variable:", choices = NULL)
),
mainPanel(
plotlyOutput('plot_pie')
)
),
##### line plot
tabItem(tabName = "lineplot",
sidebarPanel(
selectInput("in_sel_line_yVar","y Variable:", choices = NULL),
selectInput("in_sel_line_xVar","x Variable:", choices = NULL)
),
mainPanel(
plotlyOutput('plot_line')
)
),
##### scatter plot
tabItem(tabName = "scatterplot",
sidebarPanel(
selectInput("in_sel_scatter_yVar","y Variable:", choices = NULL),
selectInput("in_sel_scatter_xVar","x Variable:", choices = NULL)
),
mainPanel(
plotOutput('plot_scatter'),
textOutput('text_scatter')
)
)
)
)
ui<-dashboardPage(
dashboardHeader(title='my graph'),
sidebar,
body
)
######################3. 서버단 개발 ########################################
server <- function(input, output,session) {
options(warn = -1)
options(shiny.maxRequestSize = 30*1024^2)
dataload<-reactive({
req(input$file1)
file1 = input$file1
data1 = read.csv(file1$datapath)
updateSelectInput(session, "in_sel_bar_xVar", choices = colnames(data1))
updateSelectInput(session, "in_sel_bar_yVar", choices = colnames(data1))
updateSelectInput(session, "in_sel_pie_xVar", choices = data1[,1])
updateSelectInput(session, "in_sel_line_xVar", choices = colnames(data1))
updateSelectInput(session, "in_sel_line_yVar", choices = colnames(data1))
updateSelectInput(session, "in_sel_scatter_xVar", choices = colnames(data1))
updateSelectInput(session, "in_sel_scatter_yVar", choices = colnames(data1))
return(data1)
})
####nomal_bar
output$plot_bar <- renderPlot({
table_in<-dataload()
xdata<-as.factor(table_in[,input$in_sel_bar_xVar])
ydata<-as.factor(table_in[,input$in_sel_bar_yVar])
fdata=data.frame(x=xdata,y=ydata)
ggplot(fdata) +
geom_bar(aes_string(x='x',y='y',fill='x'),stat = "identity",show.legend=F)
})
output$plot_pie <- renderPlotly({
table_in<-dataload()
plot_ly(table_in, labels = ~colnames(table_in)[-1], values=~as.factor( table_in[table_in[,1] == input$in_sel_pie_xVar,-1] ),type='pie')
})
output$plot_line <- renderPlotly({
table_in<-dataload()
x <- list(title = input$in_sel_line_xVar)
y <- list(title = input$in_sel_line_yVar)
plot_ly(data = table_in,x=~table_in[,input$in_sel_line_xVar],y=~table_in[,input$in_sel_line_yVar],type='scatter',mode='dot')%>%
layout(xaxis = x, yaxis = y)
})
output$plot_scatter <- renderPlot({
table_in<-dataload()
xyplot(table_in[,input$in_sel_scatter_yVar]~table_in[,input$in_sel_scatter_xVar], grid=T,type=c('p','smooth'),col.line='darkorange',lwd=2, xlab=input$in_sel_scatter_xVar,ylab=input$in_sel_scatter_yVar)
})
output$text_scatter <- renderText({
table_in<-dataload()
paste("The correlation between the two is: ", cor(table_in[,input$in_sel_scatter_yVar],table_in[,input$in_sel_scatter_xVar]))
})
}
######################### 4. 샤이니 실행 ###############################
shinyApp(ui = ui, server = server)
'R' 카테고리의 다른 글
샤이니에 데이터 테이블 표시하는 방법 (0) | 2019.03.09 |
---|---|
그래프(사분위수, 지도그래프, 워드클라우드) (0) | 2019.03.09 |
그래프(원형,막대) (0) | 2019.03.09 |
SHINY 해체 (0) | 2019.03.09 |
SQL과 R과 비교(서브쿼리) (0) | 2019.03.09 |