生物信息学与算法R语言作图技术

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

2020-04-30  本文已影响0人  生信编程日常

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


1. ggplot2实现

以mtcars数据集为例:

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实现
library(ggpubr)

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

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

library(ggpubr)

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

欢迎大家关注公众号!


上一篇 下一篇

猜你喜欢

热点阅读