强烈推荐《HelloBD》和《庄闪闪的R语言手册》这两个公众号,很适合新手小白!如果对R语言有一定了解且很感兴趣的,可以经常逛逛《统计之都》,你一定会有很多收获,认识到很多志同道合的大佬!
数据可视化——以2010年世界杯球员信息为例
#加载包
library(dplyr)
library(ggplot2)
library(faraway)
#加载数据
data(worldcup)
head(worldcup)
1. 每个国家的球员数量(条形图)
player <- worldcup %>%
group_by(Team) %>%
summarise(value=n()) %>%
arrange(desc(value)) %>%
as.data.frame()
player_plot <- ggplot(player,aes(x = reorder(Team,value),y = value)) +
theme_bw(base_family = "STKaiti") +
geom_bar(aes(fill=value),stat = "identity",show.legend = F) +
coord_flip() +
scale_fill_gradient(low = "blue",high = "red") +
labs(x="国家",y="球员数量",title = "每个国家的球员数量") +
theme(axis.text.x = element_text(vjust = 0.5),plot.title = element_text(hjust = 0.5))
player_plot
条形图
2. 球员的分布情况(地图)
R语言画地图——统计之都
R语言画中国地图
REmap包画热力图
library(maps)
library(REmap)
colnames(player)<-c("nation","number")
options(remap.js.web=T)
map <- remapC(player,
maptype='world',
color=c('red','blue'),
theme=get_theme("Sky"),
maxdata=20,
mindata=14)
print(map)
地图
3. 上场时间和传球次数的关系(散点图)
p <- ggplot(worldcup,aes(x = Time,y = Passes)) +
theme_bw(base_family = "STKaiti") +
geom_point(aes(shape = Position)) +
labs(x="上场的总时间数(min)",y="传球次数") +
theme(axis.text.x = element_text(hjust = 0.5))
options(repr.plot.width=10, repr.plot.height=6)
p
散点图
4. 不同国家、不同位置的射门次数(直方图)
p <- ggplot(worldcup,aes(x = Team,y = Shots)) +
theme_bw(base_family = "STKaiti") +
geom_histogram(aes(fill=Position),stat = "identity") +
labs(x="国家",y="射门次数",title = "不同国家球员的射门情况") +
theme(axis.text.x = element_text(hjust = 0.5,angle = 90),plot.title = element_text(hjust = 0.5))
p
直方图
5. 不同位置球员的射门情况(箱线图)
p <- ggplot(worldcup,aes(x = Position,y = Shots)) +
theme_bw(base_family = "STKaiti") +
geom_boxplot(aes(fill=Position),show.legend = F) +
labs(x="不同位置",y="射门次数",title = "不同位置的射门情况") +
theme(axis.text.x = element_text(hjust = 0.5),plot.title = element_text(hjust = 0.5))
p
箱线图
6. 位置、射门、传球、铲球、救球之间的关系(散点矩阵图)
library(GGally)
p <- ggpairs(worldcup,columns=c(2,4:7),aes(color=Position),alpha=0.8) +
theme_bw(base_family="STKaiti") +
labs(title = "散点矩阵图") +
theme(plot.title=element_text(hjust=0.5))
p
散点矩阵图