factor(变量)
因子类型的转化
R语言绘图
使用ggplot2绘图
导入依赖
library(ggplot2)
绘制柱状图
> mtcars$gear
[1] 4 4 4 3 3 3 3 4 4 4 4 3 3 3 3 3 3 4 4 4 3 3 3 3 3 4 5 5 5 5 5 4
> class(mtcars$gear)
[1] "numeric"
> barplot(mtcars$gear)
- 统计一组数中元素的情况
> table(mtcars$gear)
3 4 5
15 12 5
> counts = table(mtcars$gear)
> barplot(counts)
添加横坐标标签和定义柱状图颜色
> barplot(counts, names.arg = c("3 gears","4 gears", "5 挡"))
> barplot(counts, names.arg = c("3 gears","4 gears", "5 挡"), col="red")
> barplot(counts, names.arg = c("3 gears","4 gears", "5 挡"), col="lightblue")
> barplot(counts, names.arg = c("3 gears","4 gears", "5 挡"), col="pink")
标签显示变成竖直
> par(las=2)
> barplot(counts, names.arg = c("3 gears","4 gears", "5 挡"), col="pink")
多个条状图绘制
上面这样没有图例很难辨认数据的情况
指定字段绘制图形
> counts1 = table(mtcars$cyl, mtcars$gear)
> counts1
3 4 5
4 1 8 2
6 2 4 1
8 12 0 2
> barplot(counts1, names.arg = c("3 gears","4 gears", "5 gears"), col=c("pink", "blue", "yellow"),legend=rownames(counts1))
> rownames(counts1)
[1] "4" "6" "8"
自定义图例 传入一个向量
> barplot(counts1, names.arg = c("3 gears","4 gears", "5 gears"), col=c("pink", "blue", "yellow"),legend=c("4 cyl", "6 cyl","8 cyl"))
指定 beside = TRUE
> barplot(counts1, names.arg = c("3 gears","4 gears", "5 gears"), col=c("pink", "blue", "yellow"),legend=c("4 cyl", "6 cyl","8 cyl"), beside = TRUE)
ggplot绘图"套路"
> ggplot(mtcars) # ggplot函数没有任何显示, 这里只是做数据集等准备操作
> p = ggplot(mtcars)
> p + geom_bar()
错误: stat_count() requires an x or y aesthetic.
Run `rlang::last_error()` to see where the error occurred.
> p = ggplot(mtcars, aes(x=factor(cyl))) #指定 cyl为横坐标
> p + geom_bar()
更换数据集mpg绘图
> p1 = ggplot(mpg, aes(class))
> aes(class)
Aesthetic mapping:
* `x` -> `class`
> table(mpg$class)
2seater compact midsize minivan pickup subcompact suv
5 47 41 11 33 35 62
> p1 + geom_bar()
p1 = ggplot(mpg, aes(class))
# p1 + geom_bar(aes(weight=displ))
p1 + geom_bar(aes(weight=year)) # 这里是属于这类所有值的相加
双重条形图
p1 = ggplot(mpg, aes(class))
p1 + geom_bar(aes(fill= drv)) # fill 是让ggplot自动根据因子的水平分数分配颜色等值
指定为水平条状图
p1 = ggplot(mpg, aes(class))
# p1 + geom_bar(aes(fill= drv)) # fill 是让ggplot自动根据因子的水平分数分配颜色等值
# 水平
p1 + geom_bar(aes(fill= drv), position = position_stack(reverse = TRUE))+ coord_flip() + theme(legend.position = "bottom")
直方图
> hist(mtcars$wt)
# 变成总面积为1的概率分布直方图
> hist(mtcars$wt, freq = F)
直方图参数增加
br 横坐标刻度范围 xlab横轴标签 main是标题
hist(mtcars$wt, freq = F, br=seq(0, 6, by =0.5),col = 'red', xlab = 'weight of cars', main = '车重直方图')
举一反三
> barplot(mtcars$wt, xlab = "车的重量", ylab = "数量", main = "数据标题", col = 'yellow')
网友评论