前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ggplot2绘制阴影条带哑铃图

ggplot2绘制阴影条带哑铃图

作者头像
R语言数据分析指南
发布2024-01-17 14:12:40
1050
发布2024-01-17 14:12:40
举报

加载R包

代码语言:javascript
复制
library(scales)
library(tidyverse)

导入数据

代码语言:javascript
复制
df <- read_csv("values.csv")

数据清洗

代码语言:javascript
复制
df <- df %>%
  mutate(across(2:4, ~ .x / 100)) %>%
  arrange(Overall) %>%
  mutate(order = row_number()) %>%
  mutate(Institution = fct_reorder(Institution, order)) %>%
  rename(cont = 1, overall = 2, x1 = 3, x2 = 4) %>%
  mutate(diff = abs(x2 - x1)) %>%
  mutate(x1pr = scales::percent(x1, accuracy = 1),
         x2pr = scales::percent(x2, accuracy = 1),
         dipr = scales::percent(diff, accuracy = 1),
         ovpr = scales::percent(overall, accuracy = 1)) %>%
  mutate(x1nu = if_else(x1 > x2, 1, if_else(x1 < x2, -1, -1)) / 16,
         x2nu = -1 * x1nu)

数据整合

代码语言:javascript
复制
df2 <- df %>% filter(row_number() %% 2 == 0) %>%
  mutate(xmin = -2, xmax = 2)

df <- left_join(df, df2, by = colnames(df)) %>% head(10)

数据可视化

代码语言:javascript
复制
ggplot(df, aes(y = cont))+
  geom_rect(aes(xmin=xmin, xmax=xmax, ymin=as.numeric(cont)-1.5, ymax=as.numeric(cont)-.5),
            fill="#f6f6f6")+
  geom_text(label = "Institution", x = -.675, y = dim(df)[1]+1, size = txt.sz, color =  "black", fontface = 2, hjust = 0)+
  geom_text(label = "Overall", x = 1.075, y = dim(df)[1]+1, size = txt.sz, color =  "black", fontface = 2)+
  geom_text(label = "\u0394", x = 1.2, y = dim(df)[1]+1, size = txt.sz, color =  "black", fontface = 2)+
  geom_text(aes(x = x1, label = x1pr), size = txt.sz, color = "#E6956F", nudge_x = df$x1nu)+
  geom_text(aes(x = x2, label = x2pr), size = txt.sz, color = x2.col, nudge_x = df$x2nu)+
  geom_text(aes(x = x1*0+1.075, label = ovpr), size = txt.sz, color =  "black") +
  geom_text(aes(x = x1*0+1.2, label = dipr), size = txt.sz, color =  "black")+
  geom_segment(aes(x = x1, xend = x2, yend = cont), color = "gray40", size=1)+
  geom_point(aes(x=x1), shape = 16, size = 2.5, color = "#E6956F")+
  geom_point(aes(x=x2), shape = 16, size = 2.5, color = "#E6956F")+
  scale_y_discrete(expand = c(0, 0))+
  scale_x_continuous()+
  coord_cartesian(ylim = c(0.2, 12.5), xlim = c(0,1.2), clip = 'off')
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2024-01-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 R语言数据分析指南 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 加载R包
  • 导入数据
  • 数据清洗
  • 数据整合
  • 数据可视化
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档