欢迎关注R语言数据分析指南
❝本节来介绍如何在绘制图形中添加曲形文本,以往都是通过调整文本角度来展示看起来非常别扭但是使用「geomtextpath」包就显得丝滑了很多。下面小编就通过一个案例来进行展示数据为随意构建无实际意义仅作图形展示用,希望各位观众老爷能够喜欢。 ❞
加载R包
代码语言:javascript复制library(tidyverse)
library(scales)
library(ggtext)
library(ggp)
library(geomtextpath)
导入数据
代码语言:javascript复制data <- read_tsv("data.xls")
数据清洗
代码语言:javascript复制df <- data %>%
filter(country == "USA") %>% # 筛选出国家为"USA"的数据
filter(status %in% c("Operating", "Planned", "In development", "Under Construction")) %>% # 筛选出状态为"Operating"、"Planned"、"In development"、"Under Construction"的数据
select("country", "height", "status") %>% # 选择"country"、"height"和"status"这三列数据
mutate(new_status = ifelse(status == "Operating", "In Operation", "Coming Soon")) %>% # 根据"status"列的值创建新的"new_status"列,如果"status"为"Operating",则为"In Operation",否则为"Coming Soon"
group_by(new_status) %>% # 按"new_status"分组
tally(height) %>% # 统计每个"new_status"对应的高度值的数量
mutate(csum = rev(cumsum(rev(n))), # 计算累计高度的值
pos = n/2 lead(csum, 1), # 计算每个条形图标签的位置
pos = if_else(is.na(pos), n/2, pos)) # 如果位置为空,则将位置设置为n/2
代码语言:javascript复制df %>%
ggplot(aes(x = 5, y = n, fill = new_status, label = n)) # 使用"data.frame"中的数据创建ggplot对象,设置x轴为常数5,y轴为n列,填充颜色为new_status列,标签为n列的值
geom_col(width=0.8, color = "#f2f2f2") # 添加柱状图,设置宽度为0.8,颜色为"#f2f2f2"
geom_textpath(aes(x = 5, y = pos, label = paste(n, "feet")), # 添加文字路径图层,设置x轴为常数5,y轴为pos列,标签为n列的值加上"feet"
text_only = TRUE, angle = 90, size = 4.5, color = "black") # 仅显示文字,设置旋转角度为90度,文字大小为4.5,颜色为黑色
xlim(c(1.5, 5.5)) # 设置x轴的范围为1.5到5.5
coord_polar("y", start = 0, clip = "off") # 将坐标系设置为极坐标系,y轴从0度开始,取消边界限制
scale_fill_manual(values = c("#E6956F", "#709AE1FF")) # 手动设置填充颜色的比例尺,值分别为"#E6956F"和"#709AE1FF"
annotate(geom='richtext', x = 1.5, y = 0, size = 4, # 添加富文本注释层,设置位置为(1.5, 0),大小为4
label = "<b>Cumulative Height</b><br>4,902 feet", fill = NA, label.color = NA) # 设置标签内容为"<b>Cumulative Height</b><br>4,902 feet",填充为透明,标签颜色为透明
theme_void() # 使用空白主题
theme(text = element_text(size = 9, color = "black"), # 设置文本大小为9,颜色为黑色
legend.position = "top", # 图例位置为顶部
legend.title = element_blank(), # 图例标题为空
legend.spacing.x = unit(0.05, "cm"), # 图例水平间距为0.05厘米
legend.text = element_text(color = "black", size = 8), # 图例文本颜色为黑色,大小为8
plot.margin = unit(c(2, 2, 2, 2), "cm"), # 绘图区域的边距为2厘米
plot.background = element_blank()) # 绘图背景为空