首页 > 解决方案 > R ggplot2 geom_line 指定颜色形式的向量返回未知颜色

问题描述

我有这段代码

colors = c("score" = "#26648E")
plot = ggplot() + geom_line(data = DT, aes(x = position, y = score), stat = "summary_bin", binwidth = 1000, color = "score", group = 1) + scale_color_manual(name ="", values = colors) + facet_wrap(~chromosome, scales = "free_x")
ttle = paste0("referee score") 
plot = plot + labs(
  title = ttle) #+ theme(plot.title = element_markdown(lineheight = 1.5, size = 12), legend.text = element_markdown(size = 14))
p = plot +xlab( "position") + ylab("")
p

返回

错误:未知颜色名称:score

这不是我第一次在矢量中预先定义颜色,它一直在工作。我不明白为什么在这种特定情况下它不起作用。我知道我可以直接在 geom_line 中定义颜色,我只是想了解为什么代码不起作用。例如我有这段代码

colors = c("heterozygosity" = "#8b0000", "coverage" = "#00919c")
ggplot() + 
  geom_line(data = CT, aes(x = end, y = 3*(normalize(heterozygosity)), color = "heterozygosity")) + 
  geom_line(data = COV, aes(x = end, y = 2*(normalize(coverage)), color = "coverage")) + 
  scale_color_manual(name ="", values = colors) + 
  facet_wrap(~CHROM, scales = "free_x") 

这不会产生错误并给出所需的输出。

感谢您的任何见解

标签: rggplot2colors

解决方案


颜色属于美学,请在分配 y 轴后尝试放置它。如下所示。它应该工作

colors = c("score" = "#26648E")
plot = ggplot() + geom_line(data = DT, aes(x = position, y = score, color = "score")  stat = "summary_bin", binwidth = 1000, group = 1) + scale_color_manual(name ="", values = colors) + facet_wrap(~chromosome, scales = "free_x")
ttle = paste0("referee score") 
plot = plot + labs(
  title = ttle) #+ theme(plot.title = element_markdown(lineheight = 1.5, size = 12), legend.text = element_markdown(size = 14))
p = plot +xlab( "position") + ylab("")
p

推荐阅读