环形柱状图中为负值设置不同填充颜色的实现方案
环形柱状图按正负值区分柱子填充颜色
要实现以0为分界,将负值柱子设为蓝色、正值保留原色系的效果,核心是基于柱子数值的正负创建分组变量,再通过手动颜色映射实现区分。以下是修改后的完整代码:
数据准备(不变)
uni_data <- structure(list(from = c("Argentina", "Canada", "China", "Germany", "Malawi", "Mexico", "Poland", "Russia", "South Africa", "United Republic of Tanzania", "United States", "Zambia"), to = c("Zimbabwe", "Zimbabwe", "Zimbabwe", "Zimbabwe", "Zimbabwe", "Zimbabwe", "Zimbabwe", "Zimbabwe", "Zimbabwe", "Zimbabwe", "Zimbabwe", "Zimbabwe"), fraction_mean = c(-1.16218764988057, 0.556848791658583, -0.785724007068475, -0.668776616353553, 2.98715326478044, 0.632802483886891, -0.952039672216194, -0.275904847337713, 1.91885749928563, 2.18477200782915, -1.22917889731657, 4.4028142502411), d_long = c(0.124, 0.2794, 0.2466, 0.0785, 2.8646, 0.202, 0.1153, 0.1238, 0.2247, 1.6428, 0.1664, 2.3044), mean_exposure = c(0.219336124378027, 0.964248264036473, -0.833368763174394, -0.520689933363188, 1.45247015618433, -1.53268987398912, -1.15713981781644, 0.791178790005572, 0.482041972598713, 2.02018800214932, 1.40628459671399, 2.61998072810955)), row.names = c(1L, 5L, 6L, 9L, 14L, 15L, 17L, 19L, 22L, 25L, 26L, 27L), class = "data.frame")
修改后的绘图代码
library(tidyverse) plot_uni <- uni_data %>% group_by(from) %>% summarise( sum_length = fraction_mean, mean_exposure = mean_exposure, delta = d_long ) %>% mutate( mean_exposure = round(mean_exposure, digits = 0), # 新增:根据sum_length正负创建分组变量 fill_group = ifelse(sum_length < 0, "负值", "正值") ) plt2 <- ggplot(plot_uni) + geom_col( aes( x = reorder(str_wrap(from, 5), sum_length), y = sum_length, fill = fill_group # 映射到新的分组变量 ), position = "dodge2", show.legend = TRUE, alpha = .9 ) + geom_point( aes( x = reorder(str_wrap(from, 5),sum_length), y = mean_exposure ), size = 3, color = "gray12" ) + geom_segment( aes( x = reorder(str_wrap(from, 5), sum_length), y = 0, xend = reorder(str_wrap(from, 5), sum_length), yend = 6 ), linetype = "dashed", color = "gray12" ) + coord_polar() + labs(x=" ", y=" ") plt3 <- plt2 + scale_y_continuous( limits = c(-1, 6), expand = c(0, 0), breaks = c(0,2, 3, 4) ) + # 手动指定颜色:负值设为蓝色,正值保留原紫粉色系 scale_fill_manual( "数值类型", values = c( "负值" = "#1f77b4", # 蓝色,可自行替换为喜欢的蓝色系代码 "正值" = "#C06C84" # 原色系中的紫色,若要保留渐变可调整为scale_fill_gradientn结合分组 ) ) + guides( fill = guide_legend(title.position = "top", title.hjust = .5) ) + theme( axis.title = element_blank(), axis.ticks = element_blank(), axis.text.y = element_blank(), axis.text.x = element_text(color = "gray12", size = 10), legend.position = "bottom", ) plt3
关键修改说明
- 新增分组变量:在
plot_uni数据处理中添加fill_group,通过ifelse判断sum_length是否小于0,将柱子分为正负两组。 - 调整填充映射:将
geom_col的fill参数从原delta改为新的fill_group,实现按正负值区分颜色。 - 手动颜色设置:用
scale_fill_manual直接指定负值为蓝色、正值为原色系颜色,替代原有的渐变填充。如果需要保留正值的渐变效果,可以结合fill_group和delta做分层映射,或者使用scale_fill_gradientn设置断点在0处。
内容的提问来源于stack exchange,提问作者MoonS
相关产品推荐
相关产品推荐

