ggplot2没有在图例值中分配颜色
Posted
技术标签:
【中文标题】ggplot2没有在图例值中分配颜色【英文标题】:ggplot2 not getting colors assigned in legend values 【发布时间】:2021-08-26 18:43:03 【问题描述】:我已经为绘图生成了以下代码:
ggplot(Table_Final_v0, aes(x=log2(SeqCount_a+1), y=log2(SeqCount_m1+1), fill=kingdom2, color=Color_point2)) +
geom_point(size=Size_point, alpha=0.8, color=Color_point2) + scale_color_manual(values = Color_point2) +
theme_classic() + ylab("log2(Sequence Count -m 1)\n") + xlab("\nlog2(Sequence Count -a)") + ylim(0,14) + xlim(7,17) +
geom_text(label=species, nudge_x = -0.5, nudge_y = 0.5, check_overlap = T, show.legend = F, color="black") +
theme(axis.text.x = element_text(size=10), axis.title=element_text(size=12),
axis.text.y =element_text(size=10),plot.margin = margin(1, 0.5, 0.5, 1, "cm")) + ggtitle(title) +
theme(plot.title = element_text(size = 14)) + theme(legend.title=element_blank())
这会产生以下情节:
Table_Final_v0 看起来像这样:
rRNA Seq_count_m1 Seq_count_a Size_point species kingdom2 Color_point2
Loxodonta_africana 178 18722 6 Laf Elephant red3
Acyrthosiphon_pisum 0 50324 4 Api Insects dodgerblue3
Aedes_aegypti 0 36776 4 Aae Insects dodgerblue3
Aegilops_tauschii 26 17539 4 Ata Plants forestgreen
. . . . . . .
. . . . . . .
如您所见,kingdom2
变量包含出现在图例中的名称,Color_point2
变量包括我想在绘图和图例中显示的颜色。但不知何故,我无法将它们分配给图例,它们只出现在情节中。
代码有什么问题?我希望颜色也出现在图例中的每个标签中,就像它应该使用 scale_color_manual
【问题讨论】:
【参考方案1】:这可能是完成任务的一种选择。
ggplot(df, aes(x=log2(Seq_count_a+1), y=log2(Seq_count_m1+1), color=kingdom2)) +
geom_point(size=df$Size_point, alpha=0.8) +
scale_fill_manual(values = df$Color_point2) +
theme_classic() +
ylab("log2(Sequence Count -m 1)\n") +
xlab("\nlog2(Sequence Count -a)") +
ylim(0,14) +
xlim(7,17) +
geom_text(label=df$species, nudge_x = -0.5, nudge_y = 0.5, check_overlap = T, show.legend = F, color="black") +
theme(axis.text.x = element_text(size=10),
axis.title.x = element_text(size=12),
axis.text.y = element_text(size=10),
plot.margin = margin(1, 0.5, 0.5, 1, "cm"),
legend.title=element_blank()
)
数据:
df <- tribble(
~rRNA, ~Seq_count_m1, ~Seq_count_a, ~Size_point, ~species, ~kingdom2, ~Color_point2,
"Loxodonta_africana", 178, 18722, 6, "Laf", "Elephant", "red3",
"Acyrthosiphon_pisum", 0, 50324, 4, "Api", "Insects", "dodgerblue3",
"Aedes_aegypti", 0, 36776, 4, "Aae", "Insects", "dodgerblue3",
"Aegilops_tauschii", 26, 17539, 4, "Ata", "Plants", "forestgreen")
【讨论】:
以上是关于ggplot2没有在图例值中分配颜色的主要内容,如果未能解决你的问题,请参考以下文章
R语言ggplot2可视化:在ggplot2中将图例(legend)移到图内自定义图例所处的位置自定义图例背景图例所处边框的颜色