首页 文章

编号点标签加上散点图中的图例

提问于
浏览
1

我试图使用数字(1,2,3,...)在R( ggplot2 )中的散点图中标记点,然后将数字与图例中的名称匹配(1 - Alpha,2 - Bravo,3 - Charlie . ..),作为在情节上处理太多,太长标签的一种方式 .

我们假设这是a.df:

Name      X Attribute   Y Attribute  Size Attribute  Color Attribute
Alpha     1             2.5          10              A
Bravo     3             3.5          5               B
Charlie   2             1.5          10              C
Delta     5             1            15              D

这是一个标准的散点图:

ggplot(a.df, aes(x=X.Attribute, y=Y.Attribute, size=Size.Attribute, fill=Colour.Attribute, label=Name)) +
   geom_point(shape=21) +
   geom_text(size=5, hjust=-0.2,vjust=0.2)

有没有办法改变它如下?

  • 有标有数字的散点图(1,2,3 ......)

  • 在绘图旁边有一个图例,将图标签(1,2,3 ...)分配给a.df $ Name

在下一步中,我想为点大小和颜色分配其他属性,这可能会排除一些“黑客” .

2 回答

  • 1

    这是一个替代解决方案,它将标签绘制为 geom_text . 我借用了ggplot2 - annotate outside of plot .

    library(MASS)  # for Cars93 data
    library(grid)
    library(ggplot2)
    
    d <- Cars93[1:30,]
    d$row_num <- 1:nrow(d)
    d$legend_entry <- paste("  ", d$row_num, d$Manufacturer, d$Model)
    
    ymin <- min(d$Price)
    ymax <- max(d$Price)
    y_values <- ymax-(ymax-ymin)*(1:nrow(d))/nrow(d)
    
    p <- ggplot(d, aes(x=Min.Price, y=Price)) +
            geom_text(aes(label=row_num)) +
            geom_text(aes(label=legend_entry, x=Inf, y=y_values, hjust=0)) +
            theme(plot.margin = unit(c(1,15,1,1), "lines"))
    
    gt <- ggplot_gtable(ggplot_build(p))
    gt$layout$clip[gt$layout$name == "panel"] <- "off"
    grid.draw(gt)
    

    R plot

  • 1

    这非常hacky,但可能有所帮助 . 情节标签只是由 geom_text 添加,为了产生图例,我将颜色映射到数据中的标签 . 然后为了停止被着色的点,我用 scale_colour_manual 覆盖它,您可以在其中设置点的颜色以及图例上的标签 . 最后,通过设置alpha = 0,以及通常在 theme() 中的点后面的方块,我使图例中的点不可见 .

    dat <- data.frame(id = 1:10, x = rnorm(10), y = rnorm(10), label = letters[1:10])
    ggplot(dat, aes(x, y)) + geom_point(aes(colour = label)) + 
      geom_text(aes(x = x + 0.1, label = id)) +
      scale_colour_manual(values = rep("black", nrow(dat)),
                          labels = paste(dat$id, "=", dat$label)) +
      guides(colour = guide_legend(override.aes = list(alpha = 0))) +
      theme(legend.key = element_blank())
    

    enter image description here

相关问题