"R ggplot2 막대그래프 geom bar()"의 두 판 사이의 차이

4번째 줄: 4번째 줄:
<syntaxhighlight lang='r' notebook>
<syntaxhighlight lang='r' notebook>
library(ggplot2)
library(ggplot2)
# geom_bar로 간단히 막대그래프를 그릴 수 있다.
# 카운트 (또는 가중치 합계)
g <- ggplot(mpg, aes(class))
g <- ggplot(mpg, aes(class))
# 각 클래스에 해당하는 자동차의 수
g + geom_bar()
g + geom_bar()
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang='r' notebook>
<syntaxhighlight lang='r' notebook>
# 각 class의 총 엔진 배기량
g + geom_bar(aes(weight = displ))
g + geom_bar(aes(weight = displ))
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang='r' notebook>
<syntaxhighlight lang='r' notebook>
# 방향을 바꾸려면 class를 y에 매핑한다.
ggplot(mpg) + geom_bar(aes(y = class))
ggplot(mpg) + geom_bar(aes(y = class))
</syntaxhighlight>
<syntaxhighlight lang='r' notebook>
# 같은 위치에 여러 막대를 배치하면 쌓이게 되며, 쌓이는 순서는 범례를 따른다.
g + geom_bar(aes(fill = drv))
</syntaxhighlight>
<syntaxhighlight lang='r' notebook>
# 순서를 뒤집으려면 position_stack()
ggplot(mpg, aes(y = class)) +
geom_bar(aes(fill = drv), position = position_stack(reverse = TRUE)) +
theme(legend.position = "top")
</syntaxhighlight>
<syntaxhighlight lang='r' notebook>
# 의미를 표시할 때 geom_col()를 쓸 수 있다.
df <- data.frame(trt = c("a", "b", "c"), outcome = c(2.3, 1.9, 3.2))
ggplot(df, aes(trt, outcome)) +
  geom_col()
</syntaxhighlight>
<syntaxhighlight lang='r' notebook>
# geom_point()도 같은 정보를 보여주지만, y축이 0부터 시작하지 않는다.
ggplot(df, aes(trt, outcome)) +
  geom_point()
</syntaxhighlight>
<syntaxhighlight lang='r' notebook>
# 연속데이터에도 geom_bar()를 사용할 수 있는데, 특정 위치에 카운트가 표시된다.
df <- data.frame(x = rep(c(2.9, 3.1, 4.5), c(5, 10, 4)))
ggplot(df, aes(x)) + geom_bar()
</syntaxhighlight>
<syntaxhighlight lang='r' notebook>
# 참고. 동일한 데이터로 히스토그램을 그린 것
ggplot(df, aes(x)) + geom_histogram(binwidth = 0.5)
</syntaxhighlight>
</syntaxhighlight>



2021년 3월 30일 (화) 23:55 판

1 개요

R ggplot2 막대그래프
library(ggplot2)
# geom_bar로 간단히 막대그래프를 그릴 수 있다.
# 카운트 (또는 가중치 합계)
g <- ggplot(mpg, aes(class))
# 각 클래스에 해당하는 자동차의 수
g + geom_bar()
# 각 class의 총 엔진 배기량
g + geom_bar(aes(weight = displ))
# 방향을 바꾸려면 class를 y에 매핑한다.
ggplot(mpg) + geom_bar(aes(y = class))
# 같은 위치에 여러 막대를 배치하면 쌓이게 되며, 쌓이는 순서는 범례를 따른다.
g + geom_bar(aes(fill = drv))
# 순서를 뒤집으려면 position_stack()
ggplot(mpg, aes(y = class)) +
 geom_bar(aes(fill = drv), position = position_stack(reverse = TRUE)) +
 theme(legend.position = "top")
# 의미를 표시할 때 geom_col()를 쓸 수 있다.
df <- data.frame(trt = c("a", "b", "c"), outcome = c(2.3, 1.9, 3.2))
ggplot(df, aes(trt, outcome)) +
  geom_col()
# geom_point()도 같은 정보를 보여주지만, y축이 0부터 시작하지 않는다.
ggplot(df, aes(trt, outcome)) +
  geom_point()
# 연속데이터에도 geom_bar()를 사용할 수 있는데, 특정 위치에 카운트가 표시된다.
df <- data.frame(x = rep(c(2.9, 3.1, 4.5), c(5, 10, 4)))
ggplot(df, aes(x)) + geom_bar()
# 참고. 동일한 데이터로 히스토그램을 그린 것
ggplot(df, aes(x)) + geom_histogram(binwidth = 0.5)

2 같이 보기

3 참고

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}