❝本节来介绍如何使用ggstar包绘制心形并通过哑铃图的形式来展示美国情人节消费支出,数据为随意构建,整个过程仅参考。希望对各位观众老爷能有所帮助。
加载R包
代码语言:javascript复制library(ggstar)
library(tidyverse)
R包版本号
版本号尽量保持一致,不然可能会有报错参生
代码语言:javascript复制sessionInfo()
代码语言:javascript复制other attached packages:
[1] lubridate_1.9.3 forcats_1.0.0 stringr_1.5.1 dplyr_1.1.4 purrr_1.0.2
[6] readr_2.1.5 tidyr_1.3.0 tibble_3.2.1 ggplot2_3.4.4 tidyverse_2.0.0
[11] ggstar_1.0.4.001
导入数据
代码语言:javascript复制gifts_gender <- read_tsv("data.xls")
数据清洗
代码语言:javascript复制df <- gifts_gender %>% select(-SpendingCelebrating) %>% pivot_longer(-Gender)
定义函数添加%
代码语言:javascript复制add_percent <- function(x) {
paste0(x, "%")
}
定义因子
代码语言:javascript复制df$name <- factor(df$name,levels = c("Candy","GreetingCards","Flowers",
"EveningOut","Jewelry","Clothing","GiftCards") %>%
rev())
构建标签位置信息
代码语言:javascript复制df_text <- df %>% select(-Gender) %>% group_by(name) %>%
summarise(across(everything(), ~ mean(.x, na.rm = TRUE)))
数据可视化
代码语言:javascript复制df %>% ggplot(aes(value,name,group=name))
geom_line(color="grey30")
geom_star(starshape=16,size=8,aes(fill=Gender),show.legend = F)
geom_text(aes(label =value), size = 3.5,color="white")
geom_text(data=df_text,aes(label = paste(name),x=value),
nudge_y = 0.45, size =4, color="black")
scale_fill_manual(values = c("#663399","#FF69B4"))
theme(axis.text.y = element_blank(),
axis.text.x = element_text(color="black",face="bold"),
axis.ticks=element_blank(),
axis.title = element_blank(),
panel.background = element_blank(),
plot.background = element_blank(),
plot.margin = unit(c(0.5, 0.5, 0.5,0.5), "cm"))