#加载函数包
library(ggplot2)
#创建数据集
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5),
sd=c(1,0.2,3,2,4)
)
#查看数据集
data
#柱状图+误差线(最基础)
ggplot(data) +
geom_bar( aes(x=name, y=value),
stat="identity",
fill="skyblue",
alpha=0.7) +
geom_errorbar( aes(x=name, ymin=value-sd, ymax=value+sd),
width=0.4,
colour="orange",
alpha=0.9,
size=1.3)
#水平形式
ggplot(data) +
geom_bar( aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.5) +
geom_errorbar( aes(x=name, ymin=value-sd, ymax=value+sd), width=0.4, colour="orange", alpha=0.9, size=1.3) +
coord_flip()
#矩形形式的误差线
ggplot(data) +
geom_bar( aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.5) +
geom_crossbar( aes(x=name, y=value, ymin=value-sd, ymax=value+sd), width=0.4, colour="orange", alpha=0.9, size=1.3)
#直线形式的误差线
ggplot(data) +
geom_bar( aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.5) +
geom_linerange( aes(x=name, ymin=value-sd, ymax=value+sd), colour="orange", alpha=0.9, size=1.3)
#直线+点形式的误差线
ggplot(data) +
geom_bar( aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.5) +
geom_pointrange( aes(x=name, y=value, ymin=value-sd, ymax=value+sd), colour="orange", alpha=0.9, size=1.3)
##柱状图要分组
#创建数据集
data <- data.frame(
name=c("a","b","c","a","b","c"),
value=sample(seq(4,15),6),
sd=c(1,1,1,1,1,1),
group=c("A","A","A","B","B","B")
)
#查看数据集
data
#绘制分组柱状图
ggplot(data, aes(x =name, y = value, fill = group)) +
geom_bar(stat = "identity",
position = position_dodge(0.75),
width=0.73)+
geom_errorbar( aes(x=name, ymin=value-sd, ymax=value+sd,group=group),
position = position_dodge(0.75),
width=0.4,
colour="orange",
alpha=0.9,
size=1.3)+
coord_cartesian(ylim=c(3,16))+ #坐标从非0开始的设置方法
labs(title = "", x = "类别", y = "值", fill = "组别")+
scale_fill_hue(c = 40) +
theme(legend.position="none")+
theme_bw()+
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank())+
theme(axis.title.x = element_text(size = 16),
axis.title.y = element_text(size = 14),
axis.text.x = element_text(size = 14),
axis.text.y = element_text(size = 14), #刻度
legend.title = element_text(size = 14), #最右边的图例字体
legend.key.size = unit(1.5, "lines")) #图例大小的调整,这里设置为占两个格子