# ggplot2 examples
# install.packages("ggplot2")
library(ggplot2)
# 데이터와 aesthetics를 정의해보자
head(iris)
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3.0 1.4 0.2 setosa
## 3 4.7 3.2 1.3 0.2 setosa
## 4 4.6 3.1 1.5 0.2 setosa
## 5 5.0 3.6 1.4 0.2 setosa
## 6 5.4 3.9 1.7 0.4 setosa
# sepal : 꽃받침 조각
# petal : 꽃잎
g<- ggplot(data=iris, aes(x = Sepal.Length, y = Sepal.Width))
g
아무것도 나오지 않는다.
그래프를 그릴려면 Geom인 형태를 정의해 줘야 한다.
# 점들을 표시한다.
g+geom_point()
점을 표시 했더니 이쁘게 나오네요
그럼 이제 각 종별로 색상을 표시해 봅시다.
# 종을 분류해 주고 이들에 대한 색상과 표식 사이즈를 결정해 준다.
g+geom_point(aes(color=Species), size=10)
다음은 회귀선을 표시해 보자
g+geom_point(aes(color=Species), size=5) +geom_smooth()
마지막으로 각 종별 그래프를 분리해 보자
g+geom_point(aes(color=Species), size=5) +geom_smooth() +facet_grid(~Species)
그래프는 날마다 일하는것들이 이것이니 설명은 생략함
만약 어떤 차트를 그려야 할지 잘 모르겠다면 아래 그림을 참조 하길 바람
설명
가장 기본이 되는 그래프이며, 기본적으로 1개 또는 2개의 축이 다른 그리프 표현에 용이함
############################
# 예제 데이
head(mtcars)
## mpg cyl disp hp drat wt qsec vs am gear carb
## Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
## Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
## Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
## Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
## Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
## Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
# [, 1] mpg Miles/(US) gallon
# [, 2] cyl Number of cylinders
# [, 3] disp Displacement (cu.in.)
# [, 4] hp Gross horsepower
# [, 5] drat Rear axle ratio
# [, 6] wt Weight (1000 lbs)
# [, 7] qsec 1/4 mile time
# [, 8] vs V/S
# [, 9] am Transmission (0 = automatic, 1 = manual)
# [,10] gear Number of forward gears
# [,11] carb Number of carburetors
ExamData01<-aggregate(. ~ cyl, data = mtcars, mean)
head(ExamData01)
## cyl mpg disp hp drat wt qsec vs
## 1 4 26.66364 105.1364 82.63636 4.070909 2.285727 19.13727 0.9090909
## 2 6 19.74286 183.3143 122.28571 3.585714 3.117143 17.97714 0.5714286
## 3 8 15.10000 353.1000 209.21429 3.229286 3.999214 16.77214 0.0000000
## am gear carb
## 1 0.7272727 4.090909 1.545455
## 2 0.4285714 3.857143 3.428571
## 3 0.1428571 3.285714 3.500000
기본을 그려 봅시다.
# Y에 대한 합계 Bar Chart
p<-ggplot(data=ExamData01, aes(x=cyl, y=mpg)) +
geom_bar(stat="identity")
p
# X에 대한 건수 Bar Chart
p<-ggplot(data=ExamData01, aes(x=cyl)) +
geom_bar(stat="count")
p
행열을 변경해 봅시다.
p<-ggplot(data=ExamData01, aes(x=cyl, y=mpg)) +
geom_bar(stat="identity") +
coord_flip()
p
Label을 달아 보자.
p<-ggplot(data=ExamData01, aes(x=cyl, y=mpg)) +
geom_bar(stat="identity") +
geom_text(aes(label=mpg), vjust=-0.3, size=3.5)
p
이제 색상을 변경해 봅시다.
p<-ggplot(data=ExamData01, aes(x=cyl, y=mpg)) +
geom_bar(stat="identity", fill="steelblue") +
geom_text(aes(label=mpg), vjust=-0.3, size=3.5)
#geom_text(aes(label=round(mpg,digits = 1)), vjust=-0.3, size=3.5)
p
demo(colors)
##
##
## demo(colors)
## ---- ~~~~~~
##
## > ### ----------- Show (almost) all named colors ---------------------
## >
## > ## 1) with traditional 'graphics' package:
## > showCols1 <- function(bg = "gray", cex = 0.75, srt = 30) {
## + m <- ceiling(sqrt(n <- length(cl <- colors())))
## + length(cl) <- m*m; cm <- matrix(cl, m)
## + ##
## + require("graphics")
## + op <- par(mar=rep(0,4), ann=FALSE, bg = bg); on.exit(par(op))
## + plot(1:m,1:m, type="n", axes=FALSE)
## + text(col(cm), rev(row(cm)), cm, col = cl, cex=cex, srt=srt)
## + }
##
## > showCols1()
##
## > ## 2) with 'grid' package:
## > showCols2 <- function(bg = "grey", cex = 0.75, rot = 30) {
## + m <- ceiling(sqrt(n <- length(cl <- colors())))
## + length(cl) <- m*m; cm <- matrix(cl, m)
## + ##
## + require("grid")
## + grid.newpage(); vp <- viewport(w = .92, h = .92)
## + grid.rect(gp=gpar(fill=bg))
## + grid.text(cm, x = col(cm)/m, y = rev(row(cm))/m, rot = rot,
## + vp=vp, gp=gpar(cex = cex, col = cm))
## + }
##
## > showCols2()
## Loading required package: grid
##
## > showCols2(bg = "gray33")
##
## > ###
## >
## > ##' @title Comparing Colors
## > ##' @param col
## > ##' @param nrow
## > ##' @param ncol
## > ##' @param txt.col
## > ##' @return the grid layout, invisibly
## > ##' @author Marius Hofert, originally
## > plotCol <- function(col, nrow=1, ncol=ceiling(length(col) / nrow),
## + txt.col="black") {
## + stopifnot(nrow >= 1, ncol >= 1)
## + if(length(col) > nrow*ncol)
## + warning("some colors will not be shown")
## + require(grid)
## + grid.newpage()
## + gl <- grid.layout(nrow, ncol)
## + pushViewport(viewport(layout=gl))
## + ic <- 1
## + for(i in 1:nrow) {
## + for(j in 1:ncol) {
## + pushViewport(viewport(layout.pos.row=i, layout.pos.col=j))
## + grid.rect(gp= gpar(fill=col[ic]))
## + grid.text(col[ic], gp=gpar(col=txt.col))
## + upViewport()
## + ic <- ic+1
## + }
## + }
## + upViewport()
## + invisible(gl)
## + }
##
## > ## A Chocolate Bar of colors:
## > plotCol(c("#CC8C3C", paste0("chocolate", 2:4),
## + paste0("darkorange", c("",1:2)), paste0("darkgoldenrod", 1:2),
## + "orange", "orange1", "sandybrown", "tan1", "tan2"),
## + nrow=2)
##
## > ##' Find close R colors() to a given color {original by Marius Hofert)
## > ##' using Euclidean norm in (HSV / RGB / ...) color space
## > nearRcolor <- function(rgb, cSpace = c("hsv", "rgb255", "Luv", "Lab"),
## + dist = switch(cSpace, "hsv" = 0.10, "rgb255" = 30,
## + "Luv" = 15, "Lab" = 12))
## + {
## + if(is.character(rgb)) rgb <- col2rgb(rgb)
## + stopifnot(length(rgb <- as.vector(rgb)) == 3)
## + Rcol <- col2rgb(.cc <- colors())
## + uniqC <- !duplicated(t(Rcol)) # gray9 == grey9 (etc)
## + Rcol <- Rcol[, uniqC] ; .cc <- .cc[uniqC]
## + cSpace <- match.arg(cSpace)
## + convRGB2 <- function(Rgb, to)
## + t(convertColor(t(Rgb), from="sRGB", to=to, scale.in=255))
## + ## the transformation, rgb{0..255} --> cSpace :
## + TransF <- switch(cSpace,
## + "rgb255" = identity,
## + "hsv" = rgb2hsv,
## + "Luv" = function(RGB) convRGB2(RGB, "Luv"),
## + "Lab" = function(RGB) convRGB2(RGB, "Lab"))
## + d <- sqrt(colSums((TransF(Rcol) - as.vector(TransF(rgb)))^2))
## + iS <- sort.list(d[near <- d <= dist])# sorted: closest first
## + setNames(.cc[near][iS], format(d[near][iS], digits=3))
## + }
##
## > nearRcolor(col2rgb("tan2"), "rgb")
## 0.0 21.1 25.8 29.5
## "tan2" "tan1" "sandybrown" "sienna1"
##
## > nearRcolor(col2rgb("tan2"), "hsv")
## 0.0000 0.0410 0.0618 0.0638 0.0667
## "tan2" "sienna2" "coral2" "tomato2" "tan1"
## 0.0766 0.0778 0.0900 0.0912 0.0918
## "coral" "sienna1" "sandybrown" "coral1" "tomato"
##
## > nearRcolor(col2rgb("tan2"), "Luv")
## 0.00 7.42 7.48 12.41 13.69
## "tan2" "tan1" "sandybrown" "orange3" "orange2"
##
## > nearRcolor(col2rgb("tan2"), "Lab")
## 0.00 5.56 8.08 11.31
## "tan2" "tan1" "sandybrown" "peru"
##
## > nearRcolor("#334455")
## 0.0867
## "darkslategray"
##
## > ## Now, consider choosing a color by looking in the
## > ## neighborhood of one you know :
## >
## > plotCol(nearRcolor("deepskyblue", "rgb", dist=50))
##
## > plotCol(nearRcolor("deepskyblue", dist=.1))
##
## > plotCol(nearRcolor("tomato", "rgb", dist= 50), nrow=3)
##
## > plotCol(nearRcolor("tomato", "hsv", dist=.12), nrow=3)
##
## > plotCol(nearRcolor("tomato", "Luv", dist= 25), nrow=3)
##
## > plotCol(nearRcolor("tomato", "Lab", dist= 18), nrow=3)
예제 만들기
ExamData02<-aggregate(hp ~ cyl+gear, data = mtcars, mean)
head(ExamData02)
## cyl gear hp
## 1 4 3 97.0000
## 2 6 3 107.5000
## 3 8 3 194.1667
## 4 4 4 76.0000
## 5 6 4 116.5000
## 6 4 5 102.0000
그래프 그리기
이제 엄청 쉽죠?
ggplot(data=ExamData02, aes(x=cyl, y=hp, fill=gear)) +
geom_bar(stat="identity")
# ggplot(data=ExamData02, aes(x=cyl, y=hp, fill=factor(gear))) +
# geom_bar(stat="identity")
ggplot(data=ExamData02, aes(x=cyl, y=hp, fill=factor(gear))) +
geom_bar(stat="identity", position=position_dodge())
ggplot(data=ExamData02, aes(x=cyl, y=hp, fill=factor(gear))) +
geom_bar(stat="identity", position = "fill")
#vjust : 막대 마지막으로 부터의 거리
#position_dodge(1.8) : 라벨 위치
#scale_fill_brewer(palette="Paired") : 색상 파렛트
#xlab : x축 이름
#ylab : y축 이름
#ggtitle : 표 제목
ggplot(data=ExamData02, aes(x=cyl, y=hp, fill=factor(gear))) +
geom_bar(stat="identity", position=position_dodge())+
geom_text(aes(label=round(hp,digit=0)), vjust=2, color="black",
position = position_dodge(1.8), size=5)+
scale_fill_brewer(palette="Paired")+
ylab("Gross_horsepower")+
xlab("cylinders")+
ggtitle("Write Title")
?ggplot
데이터 예제로 도움이 되었으면 합니다.
모두가 R를 잘 사용하는 그날까지..
Thanks & best regards