哑铃图(Dumbbell Chart),顾名思义,形似哑铃,每个数据由最低和最高值及一条连线组成,是展示数据差异的可视化图表之一。
棒棒糖图(Lollipop Chart),也称为火柴杆图,与条形图作用类似,是柱状图与散点图的结合图形,常用于比较多个类别的值之间的差异。
1、设置工作环境、加载R包
rm(list = ls())
setwd("D:\\棒棒糖图&哑铃图")#设置工作环境
# 加载R包
library(ggplot2)
library(ggprism)
2、加载数据
df <- read.table(file="data.txt",sep="\t",header=T,check.names=FALSE)

3、绘制哑铃图
#竖向排布
p1 <- ggplot(df) +
geom_segment(aes(x=group, xend=group, y=value1, yend=value2), color="grey",size=1) +#数据点之间的连线
geom_point( aes(x=group, y=value1), color='#ff9900', size=4 ) +#数据点1
geom_point( aes(x=group, y=value2), color='#146eb4', size=4 ) +#数据点2
theme_prism(palette = "pearl", #利用ggprism包调整主题
base_fontface = "plain",
base_family = "serif",
base_size = 14,
base_line_size = 0.8,
axis_text_angle = 45) +
theme(legend.position = "none") + #去除图例
xlab("XXXX") +#X轴标题
ylab("XXXX") +#Y轴标题
ggtitle("Dumbbell Chart")#标题
p1

#横向排布
p2 <- p1+ coord_flip()
p2

4、绘制棒棒糖图
# 棒棒糖图
p3 <- ggplot(df) +
geom_segment(aes(x=group, xend=group, y=85, yend=value1), color="grey",size=1) +
geom_point( aes(x=group, y=value1), size=4,color='red' ) +
geom_hline(yintercept = 85, lty=2,color = 'grey', lwd=0.8) + #辅助线
theme_prism(palette = "pearl",
base_fontface = "plain",
base_family = "serif",
base_size = 14,
base_line_size = 0.8,
axis_text_angle = 45) +
theme(legend.position = "none") +
xlab("XXXX") +
ylab("XXXX") +
ggtitle("Lollipop Chart")
p3

p4 <- ggplot(df) +
geom_segment(aes(x=group, xend=group, y=120, yend=value2), color="grey",size=1) +
geom_point( aes(x=group, y=value2,color=group), size=4 ) +
geom_hline(yintercept = 120, lty=2,color = 'grey', lwd=0.8) + #辅助线
theme_prism(palette = "pearl",
base_fontface = "plain",
base_family = "serif",
base_size = 14,
base_line_size = 0.8,
axis_text_angle = 45) +
theme(legend.position = "none") +
xlab("XXXX") +
ylab("XXXX") +
ggtitle("Lollipop Chart")
p4

5、拼图
#拼图
cowplot::plot_grid(p1, p2, p3, p4, ncol = 2)

网友评论