7种数据类型

  1. One variable - x: continuous or discrete
  2. Two variables - x & y: continuous and/or discrete
  3. Continuous bivariate distribution - x & y (both continuous)
  4. Continuous function
  5. Error bar
  6. Maps
  7. Three variables

数据必须是data.frame,行是观测,列是变量

两个作图函数qplot 和 ggplot

1. qplot() function: Draw quick plots

  1. # Load data
  2. data(mtcars)
  3. # Basic scatter plot
  4. qplot(x=mpg, y=wt, data = mtcars, geom = "point")
  5. # Scatter plot with smoothed line
  6. qplot(mpg, wt, data = mtcars, geom = c("point", "smooth"))
  7. # Change the size of points according to
  8. # the values of a continuous variable
  9. qplot(mpg, wt, data = mtcars, size = mpg)

2. ggplot() function: Build plots piece by piece

  1. ggplot(data = mtcars, aes(x=wt, y=mpg)) +
  2. geom_point() + # to draw points
  3. geom_line(data = head(mtcars), color = "red") # to draw lines

3.Save ggplots

3.1 三段式

  1. # Print the plot to a pdf file
  2. pdf("myplot.pdf") #设计保存格式pdf,png等,即名称,如myplot.pdf
  3. myplot <- ggplot(mtcars, aes(wt, mpg)) + geom_point() #作图代码
  4. print(myplot) #打印
  5. dev.off() #关闭

3.2 ggsave 同C1

  1. # 1. Create a plot: displayed on the screen (by default)
  2. ggplot(mtcars, aes(wt, mpg)) + geom_point()
  3. # 2.1. Save the plot to a pdf
  4. ggsave("myplot.pdf") #保存最近的图形
  5. # 2.2 OR save it to png file
  6. ggsave("myplot.png")