Lollipop是条形图/柱状图的一种,总体呈现效果比条形图/柱状图更加美观和易懂,一般我们用条形图展示如下:
![](https://evvail.com/wp-content/uploads/2020/05/image-3.png)
换成棒棒糖图如下:
![](https://evvail.com/wp-content/uploads/2020/05/image-4.png)
棒棒糖图绘制相对简单:
library(ggplot2)
library(ggthemes)
library(splines)
library(dplyr)
value <- abs(rnorm(10)) * 2
don <- data.frame(
X = paste0("A", seq(1, 10)),
value = value
)%>%
mutate(x=factor(X, X))
don %>%
ggplot( aes(x=X, y=value) ) +
geom_segment( aes(x=X ,xend=X, y=0, yend=value), color="grey") +
geom_point(size=3, color="#69b3a2") +
# 翻转
# coord_flip() +
theme_few() +
theme(
panel.grid.minor.y = element_blank(),
panel.grid.major.y = element_blank(),
legend.position="none"
) +
xlab("") +
ylab("lollipop plot")
![](https://evvail.com/wp-content/uploads/2020/06/image-37.png)
一个简单的棒棒糖图就绘制好了,如果是简单的图形我们用棒棒糖图,反而图形的美观度不如条形图。但是如果我们需要展示成对的比较此时用哑铃图(可以看做棒棒糖图变种)是更加直观:
![](https://evvail.com/wp-content/uploads/2020/05/Lollipop-1.png)
上图也是近两年CNS文章的标配,下面我们一步步用R来绘制上图:
library(ggplot2)
library(ggthemes)
library(splines)
library(dplyr)
value1 <- abs(rnorm(26)) * 2
don <- data.frame(
#x=LETTERS[1:26], # 假如你有100个样本定义1~100个数即可,目的是后续做拟合线用
x = seq(1, 26),
value1 = value1,
value2 = value1 + 3 + rnorm(26, sd = 1)
) %>%
rowwise() %>%
mutate(mymean = mean(c(value1, value2))) %>%
arrange(mymean) %>%
mutate(x = as.integer(x, x))
ggplot(don) +
geom_segment(aes(
x = x,
xend = x,
y = value1,
yend = value2
),
color = "grey",
size = 1.5) +
geom_point( # 添加第一个点
aes(x = x, y = value1),
group = 1,
color = rgb(0.2, 0.7, 0.1, 0.8),
size = 3
) +
geom_smooth( # 添加拟合曲线
aes(x = x, y = value1),
linetype = 3,
group = 1,
method = "loess",
formula = y ~ splines::ns(x),
color = "LightGreen", # 设置拟合线的颜色
fill = "LightGreen" # 设置填充色(置信区域)
) +
geom_line(
aes(x = x, y = value1),
group = 1,
color = rgb(0.2, 0.7, 0.1, 0.8),
# 0 = blank, 1 = solid, 2 = dashed, 3 = dotted, 4 = dotdash, 5 = longdash, 6 = twodash
linetype = 1
) +
geom_point(aes(x = x, y = value2),# 添加第二个点
color = rgb(0.7, 0.2, 0.1, 0.8),
size = 3) +
geom_smooth(
aes(x = x, y = value2),
group = 1,
linetype = 3,
method = "loess",
formula = y ~ splines::ns(x),
color = "RosyBrown1",
fill = "RosyBrown1"
) +
geom_line(
aes(x = x, y = value2),
group = 2,
color = rgb(0.7, 0.2, 0.1, 0.8),
linetype = 1
) +
#coord_flip()+ # 如果需要翻转图形,请去掉此处注释
theme_few() +
xlab("") +
ylab("Value of Y") + # 设置Y轴标题
scale_x_discrete(limits = LETTERS[1:26]) # 最后将坐标轴换回我们原始的名称,(此处需要和开始seq的数量对应)
写在最后,所有的图形可视化的目的都是为了更加清楚的展示你的数据信息,使其更加直观!
参考资料:
1.https://www.data-to-viz.com/graph/lollipop.html