【问题标题】:How to draw an empty ggplot with just the legend?如何仅用图例绘制一个空的ggplot?
【发布时间】:2020-09-06 10:39:46
【问题描述】:

我的问题和this question很相似,但又不一样。

我正在寻找一种方法来创建一个只有图例的空 ggplot。但是,与我在顶部链接的问题的自动名称相反,我实际上需要创建 只是图例,而图像中没有绘图区域

我尝试了以下代码:

ggplot(NULL, aes(color = ""))+
    geom_blank()+
    scale_color_manual(values = "black", labels = "Something")+
    guides(color = guide_legend())+
    theme(legend.box.background = element_rect(color = "black"))

但我得到的结果与我想要的相反 - 我得到一个没有图例的空地块区域,如下所示:

我希望我的最终结果看起来像这样(我在 Paint 中画了这个):

任何帮助将不胜感激!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以制作一个正常的情节,然后玩主题以达到预期的效果。

    library(ggplot2)
    
    ggplot(data.frame(x = 1, y = 1, colour = 'Something'), aes(x, y, fill = colour))+
      geom_point(alpha=0, shape = 0)+ # completely transparent rectangular point 
      scale_fill_manual(values='black', drop=FALSE) +
      guides(fill = guide_legend(override.aes = list(alpha=1, size = 40)))+ # showing the point in the legend
      theme(axis.title = element_blank(),
            axis.text = element_blank(),
            axis.ticks = element_blank(),
            legend.position = c(0.5, 0.5), # move the legend to the center
            legend.title = element_blank(),
            legend.text = element_text(size = 40),
            legend.key = element_rect(fill='NA'),
            panel.grid = element_blank(),
            panel.border = element_rect(colour = "black", fill='white', size=1)
      )
    

    【讨论】:

      【解决方案2】:

      得到你想要的图例,然后用cowplot::get_legend提取它:

      library(grid)
      library(cowplot)
      library(ggplot2)
      
      grid.newpage()
      grid.draw(get_legend(
        ggplot(data.frame(x = 1, y = 1), aes(x, y, fill = "Something")) +
          geom_col(size = 20)+
          scale_fill_manual(values = "white", labels = "Something", name = "") +
          theme_bw() +
          theme(legend.box.background = element_rect(color = "black"),
                legend.title = element_text(size = 30),
                legend.key.size = unit(60, "points"),
                legend.text = element_text(size = 24),
                legend.key = element_rect(colour = "black"),
                legend.box.margin = margin(20, 20, 20, 20))))
      

      【讨论】:

        猜你喜欢
        • 2019-03-13
        • 1970-01-01
        • 1970-01-01
        • 2021-04-01
        • 1970-01-01
        • 2020-05-20
        • 2012-08-15
        • 2020-10-22
        • 1970-01-01
        相关资源
        最近更新 更多