ggplot2 / ggpubr 实现发散型棒棒糖图

2020-05-08 17:11:31 浏览数 (1)

棒棒糖图 (Lollipop Chart),其实是一种特殊的barplot,只是将bar转变成了line和dot。效果如下两图所示:

1. ggplot2实现

以mtcars数据集为例:

代码语言:javascript复制
library(ggplot2)
data(mtcars)
mtcars$cyl <- factor(mtcars$cyl)
mtcars <- mtcars[order(mtcars$mpg), ]
mtcars$name <-  rownames(mtcars)
mtcars$name <- factor(mtcars$name, levels = rownames(mtcars))

ggplot(mtcars, aes(x=name, y=mpg, color = cyl, label=mpg))   
  geom_point(stat='identity', size=6)   
  geom_segment(aes(y = 0, 
                   x = name, 
                   yend = mpg, 
                   xend = name), 
               color = "gray")  
  geom_text(color="white", size=2)  
  labs(title="Lollipop Chart")   
  theme_bw()   
  coord_flip() 

可修改geom_segment(aes(y = 20))修改中间的基准线:

2. ggpubr实现
代码语言:javascript复制
library(ggpubr)

ggdotchart(mtcars, x = "name", y = "mpg",
           color = "cyl",                               
           sorting = "ascending",     # ggpubr中可以直接排序                   
           add = "segments",                             
           xlab=""
)

rotate转变为垂直方向,group实现分组,dot.size修改点的大小:

代码语言:javascript复制
library(ggpubr)

ggdotchart(mtcars, x = "name", y = "mpg",
           color = "cyl",                               
           sorting = "ascending",                        
           add = "segments",                             
           xlab="", 
           rotate = TRUE,
           group = "cyl", 
           dot.size = 3 
           
)

0 人点赞