查看原文
其他

常用 7 大类型图形可视化——排序关系图形

我才是赵西西 庄闪闪的R语言手册 2023-07-26

点击下方公众号,回复资料分享,收获惊喜

引言

在进行数据分析时,免不了对结果进行可视化。那么,什么样的图形才最适合自己的数据呢?一个有效的图形应具备以下特点:

  • 能正确传递信息,而不会产生歧义;
  • 样式简单,但是易于理解;
  • 添加的图形美学应辅助理解信息;
  • 图形上不应出现冗余无用的信息。

本系列推文,小编将汇总可视化中常用 7 大类型图形,供读者参(有些图形也会给出其他拓展的 R 包)。每类制作成一篇推文,主要参考资料为:Top 50 ggplot2 Visualizations[1]。前几期可见:

1. 可视化系列汇总——相关关系图形

2. 常用 7 大类型图形可视化——偏差关系图形

其他类似功能网站,资料包括:

  1. 庄闪闪的可视化笔记——常用图形[2]

  2. R Graph Gallery[3]

  3. 《R 语言教程》——ggplot 的各种图形[4]

系列目录

本文主要介绍第三部分:排序关系图形。

3 排序

3.1 有序条形图

有序条形图是按 Y 轴变量排序的条形图,X 轴变量必须转换为因子型(使用 factor() 函数),有序的处理:利用函数 order()

# 准备数据:按厂商分组计算平均城市里程。
cty_mpg <- aggregate(mpg$cty, by=list(mpg$manufacturer), FUN=mean) # aggregate
colnames(cty_mpg) <- c("make", "mileage") # change column names
cty_mpg <- cty_mpg[order(cty_mpg$mileage), ] # sort
cty_mpg$make <- factor(cty_mpg$make, levels = cty_mpg$make) # to retain the order in plot.
head(cty_mpg, 4)
ggplot(cty_mpg, aes(x=make, y=mileage)) +
geom_bar(stat="identity", width=.5, fill="tomato3") +
labs(title="Ordered Bar Chart",
subtitle="Make Vs Avg. Mileage",
caption="source: mpg") +
theme(axis.text.x = element_text(angle=65, vjust=0.6))
有序条形图

3.2 棒棒糖图

棒棒糖图传达的信息与柱状图相同。通过将粗条转变为细线,减少了杂乱,使图形看起来更美观。主要利用 geom_point()geom_segment() 函数。

ggplot(cty_mpg, aes(x=make, y=mileage)) +
geom_point(size=3) +
geom_segment(aes(x=make,
xend=make,
y=0,
yend=mileage)) +
labs(title="Lollipop Chart",
subtitle="Make Vs Avg. Mileage",
caption="source: mpg") +
theme(axis.text.x = element_text(angle=65, vjust=0.6))

3.3 点图

点图非常类似于棒棒糖图,但没有线条,并且各标签都在水平位置上。它更强调项目的顺序与实际值有关。

注意代码中的 geom_segment() 内的 x 和 xend 的设置。以及最后使用了 coord_flip() 反转坐标轴。

ggplot(cty_mpg, aes(x=make, y=mileage)) +
geom_point(col="tomato2", size=3) + # Draw points
geom_segment(aes(x=make,
xend=make,
y=min(mileage),
yend=max(mileage)),
linetype="dashed",
size=0.1) + # Draw dashed lines
labs(title="Dot Plot",
subtitle="Make Vs Avg. Mileage",
caption="source: mpg") +
coord_flip()
点图

3.4 坡度图

坡度图是比较两点之间差异的绝佳方法。目前,还没有内置函数来构建这个图形。下面的代码可以作为一个示例框架,告诉您如何绘制这个图形。

先展示下数据:

library(scales)
# 数据准备
df <- read.csv("https://raw.githubusercontent.com/selva86/datasets/master/gdppercap.csv")
colnames(df) <- c("continent", "1952", "1957")
left_label <- paste(df$continent, round(df$'1952'),sep=", ")
right_label <- paste(df$continent, round(df$'1957'),sep=", ")
df$class <- ifelse((df$'1957' - df$'1952') < 0, "red", "green")
head(df)
library(ggplot2)
p <- ggplot(df) + geom_segment(aes(x=1, xend=2, y=`1952`, yend=`1957`, col=class), size=.75, show.legend=F) +
geom_vline(xintercept=1, linetype="dashed", size=.1) +
geom_vline(xintercept=2, linetype="dashed", size=.1) +
scale_color_manual(labels = c("Up", "Down"),
values = c("green"="#00ba38", "red"="#f8766d")) + # color of lines
labs(x="", y="Mean GdpPerCap") + # Axis labels
xlim(.5, 2.5) + ylim(0,(1.1*(max(df$`1952`, df$`1957`)))) # X and Y axis limits

# Add texts
p <- p + geom_text(label=left_label, y=df$`1952`, x=rep(1, NROW(df)), hjust=1.1, size=3.5)
p <- p + geom_text(label=right_label, y=df$`1957`, x=rep(2, NROW(df)), hjust=-0.1, size=3.5)
p <- p + geom_text(label="Time 1", x=1, y=1.1*(max(df$`1952`, df$`1957`)), hjust=1.2, size=5) # title
p <- p + geom_text(label="Time 2", x=2, y=1.1*(max(df$`1952`, df$`1957`)), hjust=-0.1, size=5) # title


#设置主题
p + theme(panel.background = element_blank(),
panel.grid = element_blank(),
axis.ticks = element_blank(),
axis.text.x = element_blank(),
panel.border = element_blank(),
plot.margin = unit(c(1,2,1,2), "cm"))

图形是通过线段,竖线构成,之后添加文字。这是纯 ggplot 码出来的图形。当然现在也有现成的包可以完成。例如:CGPfunctions[5]。它可以得到的结果实例如下:

来源:https://ibecav.github.io/CGPfunctions/
来源:https://ibecav.github.io/CGPfunctions/

3.5 哑铃图

哑铃图作用:

  1. 比较两个时间点之间的相对位置(比如增长和下降);
  2. 比较两类之间的距离。

为了得到哑铃的正确顺序,Y 变量应该是一个因子,因子变量的水平应该与它在图中出现的顺序相同。

数据如下:

health <- read.csv("https://raw.githubusercontent.com/selva86/datasets/master/health.csv")
health$Area <- factor(health$Area, levels=as.character(health$Area)) # for right ordering of the dumbells
# health$Area <- factor(health$Area)
head(health)

直接使用 geom_dumbbel() 绘制哑铃图。之后就是一些细节的调整。

gg <- ggplot(health, aes(x=pct_2013, xend=pct_2014, y=Area, group=Area)) +
geom_dumbbell(color="#a3c4dc",
size=0.75,
point.colour.l="#0e668b") +
scale_x_continuous(label=percent) +
labs(x=NULL,
y=NULL,
title="Dumbbell Chart",
subtitle="Pct Change: 2013 vs 2014",
caption="Source: https://github.com/hrbrmstr/ggalt") +
theme(plot.title = element_text(hjust=0.5, face="bold"),
plot.background=element_rect(fill="#f7f7f7"),
panel.background=element_rect(fill="#f7f7f7"),
panel.grid.minor=element_blank(),
panel.grid.major.y=element_blank(),
panel.grid.major.x=element_line(),
axis.ticks=element_blank(),
legend.position="top",
panel.border=element_blank())
plot(gg)

拓展的哑铃图可以参考这个链接[6],得到的示意图如下。这里代码就不贴出来了,需要的读者自行去网站下载。主要是在基础版本上,加入阴影(geom_rect())、线段(geom_segment),竖线(geom_vline)。

来源:https://r-graph-gallery.com
来源:https://r-graph-gallery.com

小编有话说

这个系列的推文,只是给出了最简约的图形,并没有在美观上进行设计。主要让读者了解,绘制什么图形,应该使用什么函数/包。具体的美观设计,暂时不做设计,可以在主题、配色上做文章。类似的推文小编整理了些,可供参考:

1. R可视乎|ggplot常用主题风格汇总

2. 嫌弃自己的论文配色不好看?推荐一款科研配色神器!

3. 推荐几个R数据可视化用的配色网站

4. 我把莫奈的配色用到了科研绘图中

参考资料

[1]

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

[2]

庄闪闪的可视化笔记——常用图形: https://liangliangzhuang.github.io/R-tutorial/main-diagram-types.html

[3]

R Graph Gallery: https://www.r-graph-gallery.com/ggplot2-package.html

[4]

R 语言教程——ggplot 的各种图形: https://www.math.pku.edu.cn/teachers/lidf/docs/Rbook/html/_Rbook/ggplotvis.html

[5]

CGPfunctions: https://ibecav.github.io/CGPfunctions/

[6]

链接: https://r-graph-gallery.com/web-extended-dumbbell-plot-ggplot2.html

推荐: 可以保存以下照片,在b站扫该二维码,或者b站搜索【庄闪闪】观看Rmarkdown系列的视频教程。Rmarkdown视频新增两节视频(写轮眼幻灯片制作)需要视频内的文档,可在公众号回复【rmarkdown


R沟通|Rmarkdown教程(4)


R沟通|Rmarkdown教程(3)


R沟通|Rmarkdown教程(2)



您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存