7种数据类型
- One variable - x: continuous or discrete
- Two variables - x & y: continuous and/or discrete
- Continuous bivariate distribution - x & y (both continuous)
- Continuous function
- Error bar
- Maps
- Three variables
数据必须是data.frame,行是观测,列是变量
两个作图函数qplot 和 ggplot
1. qplot() function: Draw quick plots
# Load data
data(mtcars)
# Basic scatter plot
qplot(x=mpg, y=wt, data = mtcars, geom = "point")
# Scatter plot with smoothed line
qplot(mpg, wt, data = mtcars, geom = c("point", "smooth"))
# Change the size of points according to
# the values of a continuous variable
qplot(mpg, wt, data = mtcars, size = mpg)
2. ggplot() function: Build plots piece by piece
ggplot(data = mtcars, aes(x=wt, y=mpg)) +
geom_point() + # to draw points
geom_line(data = head(mtcars), color = "red") # to draw lines
3.Save ggplots
3.1 三段式
# Print the plot to a pdf file
pdf("myplot.pdf") #设计保存格式pdf,png等,即名称,如myplot.pdf
myplot <- ggplot(mtcars, aes(wt, mpg)) + geom_point() #作图代码
print(myplot) #打印
dev.off() #关闭
3.2 ggsave 同C1
# 1. Create a plot: displayed on the screen (by default)
ggplot(mtcars, aes(wt, mpg)) + geom_point()
# 2.1. Save the plot to a pdf
ggsave("myplot.pdf") #保存最近的图形
# 2.2 OR save it to png file
ggsave("myplot.png")