ggplot2自定义正负分布图文本颜色

2023-10-26 19:17:41 浏览数 (2)

欢迎关注R语言数据分析指南

图形解读

❝主要实现的功能为将条形图的填充颜色与文本颜色对应,那么对于此问题我们可以有如下的解决方法 ❞

1.根据文本内容构建分组 2.针对分组构建不同的颜色 3.构建颜色与文本之间的映射关系

加载R包

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

导入数据

代码语言:javascript复制
chocolate <- read_csv('data.csv')
mean <- mean(chocolate$rating)

数据清洗

代码语言:javascript复制
df <- chocolate  %>%
  group_by(company_location) %>% 
  summarise(n = n(),min_rating = min(rating),max_rating = max(rating),
            avg_rating = mean(rating, na.rm = T)) %>% 
  mutate(company_location = fct_reorder(company_location, avg_rating)) %>% 
  filter(n > 3) %>% 
  mutate(rating_diff = avg_rating - mean) %>% 
  filter(abs(rating_diff) >0.05) %>% as.data.frame() %>%
  mutate(group = rep(rep(c("A", "B", "C","D","H"), times = c(10, 6, 9,4,10)), length.out = 39)) %>% 
  mutate(col=case_when(group=="A" ~ "#E6956F",
                       group=="B" ~ "#788FCE",
                       group=="C" ~ "#A6BA96",
                       group=="D" ~ "#CDC3D4",
                       group=="H" ~ "#A88AD2"))

构建文本与颜色映射

代码语言:javascript复制
color_mapping <- df %>% 
  distinct(company_location, col) %>%
  deframe()

数据可视化

代码语言:javascript复制
df %>%
  ggplot()   
  geom_col(aes(x = rating_diff, y = company_location, fill = company_location),
           size = 0.25, color = "white") 
  geom_point(aes(x = rating_diff,y = company_location,color=company_location),size=5) 
  geom_text(aes(x = ifelse(rating_diff > 0, -.005, .005),y = company_location, 
                label = company_location,color = company_location,
                hjust = ifelse(rating_diff > 0, 1, 0)),size = 4) 
  geom_vline(xintercept=0,size=1,color="grey40") 
  scale_x_continuous(expand = expansion(add = c(0,.2)),
                     breaks = seq(-.4,.2, by = .2))   
  scale_y_discrete(expand = c(.025,.025)) 
  scale_fill_manual(values = color_mapping)  
  scale_color_manual(values = color_mapping) 
  coord_cartesian(clip = "off")  
  theme_minimal()  
  theme(panel.grid = element_blank(),
        plot.background = element_rect(fill="Aliceblue",color="Aliceblue"),
        axis.text.y=element_blank(),
        axis.title = element_blank(),
        legend.position = "none",
        axis.text.x = element_text(face = "bold", size =rel(1), color = "black"))

0 人点赞