r语言中mpg数据_R语言数据分析系列之五
R语言数据分析系列之五
本节来讨论一下R语言的基本图形展示,先来看一张效果图吧。
这张图是由R语言生成的虚拟效果展示图,在我的GitHub项目中提供了具体的代码实现:https://github.com/comaple/R-wordcloud.git
好了我们開始今天的旅程吧:
本节用到的包有:RColorBrewer用来生成序列颜色值, plotrix三维图形
本节用到的数据集:vcd包中的Arthritis数据集
数据集
install.packages("vcd")
library('vcd')
install.packages(plotrix) #将图形包也一并安装了
library(plotrix)
data(package='vcd') # 查看vcd包得所有数据集
class(Arthritis) # 查看数据集类型
names(Arthritis) # 查看列名
arth
arth[1:10,] #查看前10行数据
柱状图
#该数据集最后一列Improved为因子型数据。
table(arth$Improved) #查看因子水平的count值
col
A bar plot using the specified color will display the distribution of improved cases, with "improved" labeled on the x-axis and "count" on the y-axis, titled "Statistics of Improved".
柱状图绘制频数分布表数据,并设置水平排列、x轴标签为计数、y轴标签为改善以及图表标题为统计结果。
barplot(counts,col=col,legend=rownames(counts),width=0.1) #堆砌条形图
该函数用于生成带有指定颜色范围和并列分布的分组条形图,并在图形上标注行名作为图例标签
饼图
par(mfrow=c(1,2)) # 定义横向画布,两格布局
label
ages
pie(table(ages),family='STKaiti') # 画出饼图
pie(table(ages), labels = sprintf("%s:%s", levels(ages), round(table(ages)/sum(table(ages))*100, 2)), family = "STKaiti", title = "关节炎发病率年龄段占比")
Three-dimensional pie chart of age distribution data with main title: 关节炎患者年龄构成占比 and font family: STKaiti. The pie chart's label is generated by appending text (round(age distribution data / sum(age distribution data) * 100, 2) %). The explode parameter is set to 0.1 for better visualization effect.
直方图
我们採用mtcars数据集来进行图形绘制:
h
lines(density(mtcars$mpg),col='blue',lwd=2)#加入核密度图
假设要单独绘制和密度图的话能够这样:
plot(density(mtcars$mpg),main='DensityOf Car Gallon')
在图中可见的是,在研究过程中我们采用了高斯核作为核密度函数,并设置其方差参数为2.477。样本采样数量共计32例。
箱型图
该方法通过展示连续型变量的五点总结(包括下界值、第一四分位数、第二四分位数、第三四分位数以及上界值)来描绘连续型变量的分布特征
而且能够将离群点列出。
以mtcars数据集为例,在其中mpg表示每百公里油耗指标;而cyl则代表发动机的气缸数量。为了分析不同气缸数量对每加仑汽油行驶里程(mpg)的影响程度,则需要绘制相应的图表:
A box and whisker plot illustrating the distribution of miles per gallon across different numbers of cylinders is generated using the mtcars dataset. The primary title for this visualization is "Car Mileage Analysis", with the x-axis labeled as "Cylinders Count" and the y-axis labeled as "Miles Per Gallon".
通过观察图表可以看出:可以看出,在不同 cylinder 发动机性能比较中可以看到的是 4 cylinder 发动机在有效利用率方面表现最为突出。值得注意的是 6 cylinder 发动机运行最为平稳 相比之下 8 cylinder 发动机不仅效率较低 并且运行稳定性也未能达到理想水平
