언어/R

ggplot2

newlibra 2025. 1. 28. 22:28

 

install.packages("ggplot2")
library(ggplot2)

str(airquality)
#--산점도
ggplot(airquality, aes(x=Day, y=Temp)) +
  geom_point(size=3, color="red")
#--라인
ggplot(airquality, aes(x=Day, y=Temp)) +
  geom_line()
#--산점도+라인
ggplot(airquality, aes(x=Day, y=Temp)) +
  geom_point(size=3 ) +
  geom_line(color="red")
#--막대
ggplot(mtcars, aes(x=factor(cyl))) +
  geom_bar(width=0.5) +
  labs(x="cyl수", y="자동차수", title="cyl별 자동차수") 
#--누적막대
ggplot(mtcars, aes(x=factor(cyl))) +
  geom_bar(aes(fill=factor(gear)))
#--선버스트
ggplot(mtcars, aes(x=factor(cyl))) +
  geom_bar(aes(fill=factor(gear))) +
  coord_polar(theta="y")
#--상자그림
ggplot(airquality, aes(x=Day, y=Temp, group=Day)) +
  geom_boxplot()
#--히스토그램
ggplot(airquality, aes(Temp)) +
  geom_histogram(binwidth = 1)

#--사선
str(economics)
library(dbplyr)
x_inter <- filter(economics, psavert == min(economics$psavert))$date
ggplot(economics, aes(x=date, y=psavert)) +
  geom_line() +
  geom_abline(intercept = 12.18671, slope= -0.0005444) +
  geom_hline(yintercept = mean(economics$psavert)) +
  #geom_vline(xintercept = as.Date("2005-07-01")) +
  geom_vline(xintercept = x_inter)

#--레이블
ggplot(airquality, aes(x=Day, y=Temp)) +
  geom_point() +
  geom_text(aes(label=Temp, vjust=0, hjust=0))


#--anotate
ggplot(mtcars, aes(x=wt, y=mpg)) +
  geom_point() +
  annotate("rect", xmin=3, xmax=4, ymin=12, ymax=21, alpha=0.5, fill="skyblue") +
  annotate("segment", x=2.5, xend=3.7, y=10, yend=17, color="red", arrow=arrow()) +
  annotate("text", x=2.5, y=10, label="point")