R语言基础包中的绘图函数——快速用R探索数据

library(ggplot2)

#R语言中的基础包所带的绘图函数虽然用起来相对ggplot2包不是那么友好
#但在刚拿到原始数据时进行快速探索还是很方便的


####散点图
#运用plot()函数,向函数传入一个x向量和一个y向量
plot(mtcars$wt,mtcars$mpg)
#等价于
qplot(wt,mpg,data = mtcars)
#等价于
ggplot(data = mtcars,mapping = aes(x = wt,y = mpg)) + geom_point()


####折线图
#同样运用plot()函数,向函数传入一个x向量和一个y向量,同时传入参数type = "l"
plot(pressure$temperature,pressure$pressure,type = "l")
#继续向图中添加数据点和折线
points(pressure$temperature,pressure$pressure)
lines(pressure$temperature,pressure$pressure/2,col = "red")
points(pressure$temperature,pressure$pressure/2,col = "red")
#等价于
qplot(pressure$temperature,pressure$pressure,geom = c("line","point"))
#等价于
ggplot(data = pressure,mapping = aes(x = temperature,y = pressure)) + geom_line() + geom_point()


####条形图
#使用barplot()函数,并向其传递两个向量作为参数,第一个向量用来设定条形的高度
#第二个向量用来设定每个条形对应的标签(可选)
barplot(BOD$demand,names.arg = BOD$Time)
#生成频数表
barplot(table(mtcars$cyl))
#qplot()绘制条形图
#qplot(factor(BOD$Time),BOD$demand,geom="bar",stat="identity")   这里stat参数有问题
#等价于
ggplot(data = BOD,aes(Time,demand)) + geom_bar(stat = "identity")
#频数条形图
ggplot(data = mtcars,aes(x = cyl)) + geom_bar()


####直方图
#使用hist()函数,通过breaks参数指定大致组距
hist(mtcars$mpg,breaks = 10)
#等价于
ggplot(data = mtcars,aes(x = mpg)) + geom_histogram(binwidth = 4)


####箱线图
#使用plot()函数,当x为因子变量(与数值变量对应时),默认绘制箱线图
plot(ToothGrowth$supp,ToothGrowth$len)
#使用公式语法
boxplot(len ~ supp,data = ToothGrowth)
#在x轴引入两变量的交互
boxplot(len ~ supp + dose,data = ToothGrowth)
#用qplot()绘制箱线图
qplot(ToothGrowth$supp,ToothGrowth$len,geom = "boxplot")
#等价于
ggplot(data = ToothGrowth,mapping = aes(x=supp,y=len)) + geom_boxplot()
#使用三个独立的向量参数
qplot(interaction(supp,dose),len,data = ToothGrowth,geom = "boxplot")
#等价于
ggplot(data = ToothGrowth,mapping = aes(x=interaction(supp,dose),y=len)) + geom_boxplot()


####绘制函数图像
#使用curve()函数绘制,传入一个关于变量x的表达式
curve(x^3 - 5*x,from = -4,to = 4)
#自定义函数图像
my_fun <- function(xvar){
  1/(1 + exp(-xvar + 10))
}
curve(my_fun(x),from = 0, to = 20)
#添加直线
curve(1 - my_fun(x),add = TRUE,col = "red")
#等价于
#qplot(c(0,20),fun = my_fun,stat = "function",geom = "line")
#等价于
ggplot(data.frame(x=c(0,20)),aes(x=x)) + stat_function(fun = my_fun,geom = "line")

猜你喜欢

转载自blog.csdn.net/PyDarren/article/details/85045076
今日推荐