# R小姐：折线图、条形图、直方图、箱图、函数曲线

1

``````library(ggplot2)
library(gcookbook)
#绘制第一条曲线
plot(pressure\$temperature,pressure\$pressure,type = 'l')
#将数据点添加至曲线，pch表示点的形状
points(pressure\$temperature,pressure\$pressure,pch=9)
#绘制第二条曲线压力减半，颜色为红色
lines(pressure\$temperature,pressure\$pressure/2,col='red')
#添加第二条曲线的数据点，颜色为红色
points(pressure\$temperature,pressure\$pressure/2,col='red')
``````
image
``````#生成一个图形向量，用I()函数避免歧义
qplot(x=temperature,y=pressure,data = pressure,geom = c('line','point'),colour=I('blue'))
``````
image
``````#分步走传数据，绘点图，绘线图。分别添加颜色
ggplot(data = pressure,mapping = aes(x=temperature,y=pressure)) +
geom_point(colour='red') +
geom_line(colour='blue')
``````
image

2

``````#利用table生成总结数据框，然后生成条形图
barplot(table(mtcars\$cyl))
``````
image
``````#设置箱子的宽度，连续型变量绘图
qplot(x=cyl,data = mtcars,binwidth=1)
``````
image
``````#将cyl转化为因子，即离散型变量
qplot(x=factor(cyl),data = mtcars)
``````
image
``````#离散型变量并设置填充色和边框色
ggplot(data = mtcars,mapping = aes(x=factor(cyl))) +
geom_bar(colour='red',fill='lightblue')
``````
image

3

``````#绘制直方图，并将数据分为12份
hist(x=mtcars\$mpg,breaks = 10)
``````
image
``````#设置直方图的宽度和边框颜色
qplot(x=mpg,data = mtcars,binwidth=4,colour=I('white'))
``````
image
``````#设置直方图的边框、填充色和边框色
ggplot(data = mtcars,mapping = aes(mpg)) +
geom_histogram(binwidth = 4,colour='red',fill='lightblue')
``````
image

4

``````#利用公式绘制箱图
boxplot(len ~ supp + dose,data = ToothGrowth)
``````
image
``````#利用interaction将两个变量交叉绘制箱图
qplot(x=interaction(supp,dose),y=len,data = ToothGrowth,geom = 'boxplot')
``````
image
``````#变量交叉，设置填充色和边框色
ggplot(data = ToothGrowth,mapping = aes(x=interaction(supp,dose),y=len)) +
geom_boxplot(fill='lightblue',colour='red')
``````
image

5

``````
#表达式，取值范围

curve(x^2,from = -4,to = 4,col='red')

curve(x^2 + x ,add = TRUE,from = -4,to = 4,col='blue')

``````
image
``````#用函数的方法运用qplot
f <- function() {
x <- 0:20
y <- 1/(1 + exp(-x + 10))
qplot(x,y,geom = 'line')
}
f()
``````
image
``````#自建一个函数方程
myfun <- function(xval){
1/(1 + exp(-xval + 10))
}
#ggplot要求数据是数据框格式
ggplot(data.frame(x=c(0:20)),aes(x=x)) +
stat_function(fun = myfun,geom = 'line',colour='red')
``````
image

• R小姐：利用ggplot2绘制散点图

• R小姐：让数据抖动起来

• R小姐：绘制简单拟合曲线

• P公子、R小姐实战：爬取言情小说并做词云分析

image