Lecture 4 R作图实践
Bar chart 条图
#4.1 Bar chart
library(vcd)
counts = table(Arthritis$Improved)
counts
par(mfrow=c(2,2))
barplot(counts,
main = "Simple Bar Plot",
xlab = "Improvement", ylab = "Frequency")
#横向条图
barplot(counts,
main = "Horizontal Bar Plot",
xlab = "Frequency", ylab = "Improvement",
horiz = TRUE)
counts <- table(Arthritis$Improved,Arthritis$Treatment)
counts
#堆积条形图
barplot(counts,
main = "Stacked Bar Plot",
xlab = "Treatment", ylab = "Frequency",
col = c("red","yellow","green"),
legend = rownames(counts))
#复式条形图
barplot(counts,
main = "Group Bar Plot",
xlab = "Treatment", ylab = "Frequency",
col = c("red","yellow","green"),
legend = rownames(counts),beside = TRUE)
4.2 Pie chart 饼图
#Pie chart
install.packages("plotrix")
library(plotrix) #用于三维饼图
par(mfrow=c(2,2))
slices <- c(10,12,4,16,8)
lbls <- c("US","UK","Australia","Germany","France")
pie(slices, labels = lbls,
main = "Simple Pie Chart",
edges = 300,radius = 1) #面积 半径
pct <- round(slices/sum(slices)*100)
lbls2 <- paste(lbls, " ", pct, "%",sep = "") #paste 连接字符
lbls2
pie(slices, labels = lbls2,
col = rainbow(length(lbls2)),
main = "Pie Chart with Percentages",
edges = 300,radius = 1)
pie3D(slices,labels = lbls,
explode = 0.1,
main = "3D Pie Chart",
edges =300,radius=1)
mytable <- table(state.region)
lbls3 <- paste(names(mytable), "\n", mytable, sep = "")
lbls3
pie(mytable,labels =lbls3,
main = "Pie Chart from a Table\n(with sample size)",
edges=300,radius=1)
4.3 Fan Plot 扇形图
#Fan Plot
slices <- c(10,12,4,16,8)
lbls <- c("US","UK","Australia","Germany","France")
fan.plot(slices, labels = lbls, main = "Fan Plot")
4.4 Dot Chart 点图
#Dot Chart
dotchart(mtcars$mpg,
labels = row.names(mtcars),cex=0.7,
main = "Gas Mileage for Car Models",
xlab = "Miles Per Gallon")
4.5 summary
head(mtcars)
summary(mtcars) #对数据特征做简单统计
4.6 Tables
attach(mtcars)
table(cyl)
summary(mpg)
table(cut(mpg,seq(10,34,by=2)))
4.7 Correlations 相关
states <- state.x77[,1:6]
cov(states) #协方差
var(states) #方差
cor(states) #相关
4.8 T test
x <- rnorm(100,mean = 10,sd = 1)
y <- rnorm(100,mean = 30,sd = 1)
t.test(x,y,alt = "two.sided")
4.9 Wilcoxon test
wilcox.test(x,y,alt = "less")
4.10 正态性检验
library(normtest)