You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言scale_fill_manual如何指定Spectral调色板非连续三色?

解决R中从ColorBrewer调色板选择非连续颜色的问题

核心解决方法

在R中,从ColorBrewer调色板生成的颜色向量里选取非连续位置的颜色,只需在方括号中传入数值向量即可,比如用c(索引1, 索引2, 索引3)指定离散位置,而非连续范围(如1:3)。

针对你的需求——保留Spectral调色板的第1、2个颜色,将第3个替换为调色板的第8个颜色,对应的代码写法是:

brewer.pal(11, "Spectral")[c(1, 2, 8)]

修改后的完整绘图代码

将你原代码中scale_fill_manual的values参数替换为上述写法,同时清理掉重复的ggplot语句,修改后的代码如下:

library(readxl)
library(scales)
library(ggdark)
library(ggpubr)
library(ggplot2)
library(forcats)
library(reshape2)
library(RColorBrewer)

excel_pggb <- read_excel("/media/mat/Extreme SSD/TheUniversityOfFerrara/2°Year/pangenome_assembly_R.xlsx") # PGGB tab performance
## excel_mcCACTUS <- read_excel("/media/mat/Extreme SSD/TheUniversityOfFerrara/2°Year/pangenome_assembly_R.xlsx", 2) # mc-CACTUS tab performance

df_pggb <- data.frame(excel_pggb) # PGGB dataframe
## df_mcCACTUS <- data.frame(excel_HG005) # mc-CACTUS dataframe

df_pggb$tool_used <- factor(df_pggb$tool_used, levels=c('wfmash', 'seqwish', 'smoothxg')) # order of tools pggb
df_pggb$aspect <- factor(df_pggb$aspect, levels=c('real_timeH', 'cpu_timeH', 'peak_memGB')) # order of aspects pggb
## df_mcCACTUS$tool_used <- factor(df_mcCACTUS$tool_used, levels=c('', '', '', '')) # order of tools mc-CACTUS
## df_mcCACTUS$aspect <- factor(df_mcCACTUS$aspect, levels=c('real_timeH', 'cpu_timeH', 'peak_memGB')) # order of aspects pggb
df2 <- with(df_pggb, df_pggb[order(No_of_threads, tool_used, aspect),]) # collapse threads based on number used (PGGB)
## df3 <- with(df_mcCACTUS, df_mcCACTUS[order(No_of_threads, tool_used, aspect),]) # collapse threads based on number used (mc-CACTUS)

### PLOT performance of different tools of the PGGB builder
test_on_pggb <- 
  ggplot(df2, aes(x=tool_used, y=value, fill=aspect)) + 
  geom_col(position='dodge', width=.6, alpha=.6, color='black') + 
  facet_wrap(~No_of_threads, scales='free', nrow=1) + 
  theme_bw() +
  theme(plot.title=element_text(face='bold.italic', hjust=.5), 
        legend.title=element_text(face='italic'), 
        legend.position='bottom', 
        legend.direction='horizontal') + 
  scale_fill_manual(values=brewer.pal(11, "Spectral")[c(1,2,8)], 
                    labels=c('real_time_hours', 'CPU/h', 'RAM in GB')) + 
  ggtitle('PGGB_performance_by_tool') + 
  guides(fill=guide_legend(title='execution_aspect', title.position='top', title.hjust=.5))

内容的提问来源于stack exchange,提问作者Matteo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 04:30:49