ggplot2|发散性“正负”图

时间:2022-07-22
本文章向大家介绍ggplot2|发散性“正负”图,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前面介绍了一些ggplot绘图,ggplot2|从0开始绘制直方图ggplot2|从0开始绘制箱线图ggplot2|从0开始绘制折线图,这次介绍一下当数据为发散性正负值的时候,几种比较合适的展示方式。

一 载入数据并处理

library(ggplot2)
# 使用mtcars数据集
data("mtcars")  
# 保留car name ,新建一列
mtcars$car_name <- rownames(mtcars) 
# 对mpg进行标准化处理 
mtcars$mpg_z <- round((mtcars$mpg - mean(mtcars$mpg))/sd(mtcars$mpg), 2)  
# 按照0未阈值 ,分上 下
mtcars$mpg_type <- ifelse(mtcars$mpg_z < 0, "below", "above")  
mtcars <- mtcars[order(mtcars$mpg_z), ]  # 为展示美观,数据排序
# 改为因子,能够保持原顺序
mtcars$car_name <- factor(mtcars$car_name, levels = mtcars$car_name)  

注:改为因子使图形按照原顺序输出,很常用

二 Diverging bars

Diverging bars是一种可以同时处理负值和正值的条形图。注意为了使柱状图创建柱形图而不是直方图,需要确保:

(1)设置stat=identity

(2)在aes()中同时提供x和y,其中x是字符或因子,y是数值。

Diverging Barcharts

ggplot(mtcars, aes(x=car_name, y=mpg_z, label=mpg_z)) +   geom_bar(stat='identity', aes(fill=mpg_type), width=.5)  +  scale_fill_manual(name="Mileage", 
                    labels = c("Above Average", "Below Average"), 
                    values = c("above"="#00ba38", "below"="#f8766d")) +   labs(subtitle="Normalised mileage from 'mtcars'", 
       title= "Diverging Bars") +   coord_flip() + theme_bw()

三 Diverging Lollipop Chart

Lollipop Chart与上述类似,而是使用 geom_point 和 geom_segment 来获得想展示的图。

ggplot(mtcars, aes(x=car_name, y=mpg_z, label=mpg_z)) +   geom_point(stat='identity', color="orange",size=4)  +  geom_segment(aes(y = 0, 
                   x =car_name, 
                   yend = mpg_z, 
                   xend =car_name), 
               color = "grey")  +  labs(title="Diverging Lollipop Chart") +   ylim(-2.5, 2.5) +  coord_flip() + theme_bw()

四 Diverging Dot Plot

同样可以用点图传达相似的信息,圈圈里面加上具体的数值。

ggplot(mtcars, aes(x=car_name, y=mpg_z, label=mpg_z)) +   geom_point(stat='identity', aes(col=mpg_type), size=6)  +  scale_color_manual(name="Mileage",
                     labels = c("Above Average", "Below Average"),
                     values = c("above"="#00ba38", "below"="#f8766d")) +   geom_text(color="white", size=2) +  labs(title="Diverging Dot Plot",
       subtitle="Normalized mileage from 'mtcars': Dotplot") +   ylim(-2.5, 2.5) +  coord_flip() + theme_bw()

五 参考资料

http://r-statistics.co/Top50-Ggplot2-Visualizations-MasterList-R-Code.html