【问题标题】:Legend with un-plotted variable in ggplot2ggplot2 中未绘制变量的图例
【发布时间】:2019-12-16 01:48:20
【问题描述】:

我有数据,其中每个点位于两个质心之间的频谱上。我通过为每个质心指定颜色来为每个点生成一种颜色,然后将每个点的颜色设置为其两个质心之间的位置的函数。我用它来手动指定每个点的颜色,并按以下方式绘制数据:

lb.plot.dat <- data.frame('UMAP1' = lb.umap$layout[,1], 'UMAP2' = lb.umap$layout[,2],
                          'sample' = as.factor(substr(colnames(lb.vip), 1, 5)), 
                          'fuzzy.class' = color.vect))
p3 <- ggplot(lb.plot.dat, aes(x = UMAP1, y = UMAP2)) + geom_point(aes(color = color.vect)) +
  ggtitle('Fuzzy Classification') + scale_color_identity() 
p3 + facet_grid(cols = vars(sample)) + theme(legend.) + 
  ggsave(filename = 'ref-samps_bcell-vip-model_fuzzy-class.png', height = 8, width = 16)

color.vect 是前面提到的图中每个点的颜色向量)

我想生成该图的图例,给出用于每个质心的颜色。我有一个命名向量class.cols,其中包含用于每个质心的颜色,并根据相应的类命名。

有没有办法将此向量转换为绘图的图例,即使它没有在绘图调用中明确使用?

【问题讨论】:

  • 可能here的答案就是你想要的。
  • 只要您使用scale_colour_identity(),您将无法轻松生成图例,因为质心和颜色定义之间没有映射。使用每个质心一个级别的因子而不是color.vect,并使用带有合适调色板的scale_colour_dicrete(),或者如果您想手动控制每个质心使用哪种颜色,请使用scale_colour_manual()。一个可行的答案是不可能的,因为如果没有您提供数据,您的代码示例就无法运行。您需要提供一个最小或简化的代码示例和数据来单独演示问题。
  • 如果您提供了一个很好的可重现示例(reprex),这将非常有帮助:reprex.tidyverse.org/articles/reprex-dos-and-donts.html

标签: r ggplot2 plot


【解决方案1】:

您可以通过设置guide = "legend" 来开启scale_color_identity() 中的图例绘制。您必须在 scale 函数中指定中断和标签,以便图例正确说明每种颜色所代表的内容,而不仅仅是颜色的名称。

library(ggplot2)

df <- data.frame(x = 1:3, y = 1:3, color = c("red", "green", "blue"))

# no legend by default
ggplot(df, aes(x, y, color = color)) +
  geom_point() +
  scale_color_identity()


# legend turned on
ggplot(df, aes(x, y, color = color)) +
  geom_point() +
  scale_color_identity(guide = "legend")

reprex package (v0.3.0) 于 2019 年 12 月 15 日创建

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-28
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多