当前位置: 首页> 财经> 股票 > R语言ggplot2包绘制哑铃图

R语言ggplot2包绘制哑铃图

时间:2025/7/11 14:31:42来源:https://blog.csdn.net/a852232394/article/details/139296303 浏览次数:0次

数据和代码获取:请查看主页个人信息!!!

载入R包

rm(list=ls())
library(tidyverse)
library(ggalt) # devtools::install_github("hrbrmstr/ggalt")
library(scales)

数据载入

health <- read.csv("health.csv")
areas <- read.csv("areas.csv")

数据整理

health <-health %>%mutate(area_id=trunc(area_id)) %>%arrange(area_id, pct) %>%mutate(year=rep(c("2014", "2013"), 26),pct=pct/100) %>%left_join(areas, "area_id") %>%mutate(area_name=factor(area_name, levels=unique(area_name)))
​
health <- setNames(bind_cols(filter(health, year==2014), filter(health, year==2013))[,c(4,1,5)],c("area_name", "pct_2014", "pct_2013"))
  • health 数据集中的 area_id 列四舍五入为整数。

  • 根据 area_idpct 列对数据集进行排序。

  • 在数据集中添加一个 year 列,其值分别为 "2014" 和 "2013",并将 pct 列的值除以 100。

  • areas 数据集与 health 数据集进行左连接,连接键为 area_id 列。

  • area_name 列转换为因子,并按唯一值的顺序设置其水平。

  • health 数据集中的 year 为 2014 和 2013 的数据分别筛选出来,并将它们合并成新的数据集。最后,将列重命名为 "area_name"、"pct_2014" 和 "pct_2013"。

可视化

txt_col <- "black"
gg <- ggplot(health, aes(x=pct_2014, xend=pct_2013, y=area_name, group=area_name)) +geom_dumbbell(colour="#a3c4dc", size=1.5, colour_xend="#0e668b",dot_guide=TRUE, dot_guide_size=0.15) +scale_x_continuous(label=percent) +labs(x=NULL, y=NULL) +theme_bw() +theme(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())
gg
​
ggsave('pic.png', width = 5, height = 5)

 

  • ggplot() 函数指定了基本图形,并设置了 xxendygroup 的美学映射。

  • geom_dumbbell() 函数创建了 dumbbell 图,用于表示两个时间点之间的变化。参数设置了线的颜色、粗细、点的颜色和指导线的长度。

  • scale_x_continuous() 函数将 x 轴标签格式化为百分比。

  • labs() 函数设置了 x 和 y 轴的标签为 NULL。

  • theme_bw() 函数设置了基本的黑白主题,并通过 theme() 函数进一步调整了图的样式,包括背景颜色、网格线、轴标记和图例位置。

  • ggsave() 函数保存了绘制的图形到名为 "pic.png" 的文件中,指定了图形的宽度和高度。

关键字:R语言ggplot2包绘制哑铃图

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: