直方图改变柱子的顺序
# 导入基础函数包
library(ggplot2)
library(dplyr)
#创建数据集
data <- data.frame(
name=c("north","south","south-east","north-west","south-west","north-east","west","east"),
val=sample(seq(1,10), 8 )
)
#查看数据
data
##使用dplyr包中的mutate函数,对数据框data进行变量的添加和修改操作。其中,fct_reorder函数是forcats包中的函数,用于对因子变量进行重新排序
library(forcats)
#(1)
#已经计算好了每一组的个数
data %>%
ggplot( aes(x=name, y=val)) +
geom_bar(stat="identity", fill="#f68060", alpha=.6, width=.4) +
xlab("") +
theme_bw()
data %>%
mutate(name = fct_reorder(name, val)) %>% #将name变量按照val变量的大小进行重新排序(从小到大)
ggplot( aes(x=name, y=val)) +
geom_bar(stat="identity", fill="#f68060", alpha=.6, width=.4) +
xlab("") +
theme_bw()
data %>%
mutate(name = fct_reorder(name, desc(val))) %>% #将name变量按照val变量的大小进行重新排序(从大到小)
ggplot( aes(x=name, y=val)) +
geom_bar(stat="identity", fill="#f68060", alpha=.6, width=.4)
#(2)
#如果某个因子水平对应多个值(没有提前计算好每一组的个数)
mpg <- as.data.frame(mpg[,c("class","hwy")])
mpg
#按照长度画直方图
mpg %>%
mutate(class = fct_reorder(class, hwy, .fun='length')) %>%
ggplot( aes(x=class, fill=class)) +
geom_bar()
#按照均值画直方图
mpg %>%
mutate(class = fct_reorder(class, hwy, .fun='mean')) %>%
ggplot(aes(x=class, fill=class)) +
geom_bar()
#(3)
#手动规定顺序
data
data %>%
mutate(name = fct_relevel(name,
"north", "north-east", "east",
"south-east", "south", "south-west",
"west", "north-west")) %>%
ggplot( aes(x=name, y=val)) +
geom_bar(stat="identity") +
xlab("")
mpg
levels(as.factor(mpg$class))
mpg %>%
mutate(class = fct_relevel(class,
"2seater" , "minivan" , "pickup" ,
"subcompact" , "midsize" , "compact" ,
"suv" )) %>%
ggplot(aes(x=class, fill=as.factor(class) )) +
geom_bar() +
scale_fill_hue(c = 40) +
theme(legend.position="none")