簡體   English   中英

將ggplot Legend標簽直接放在其填充顏色上

[英]Position a ggplot Legend label directly over its fill colour

對於ggplot圖,我希望將圖例的值(此處為0和1)定位在它們所代表的顏色上,而不是它們的側面。 我的意思是不是在彩色正方形的左邊,右邊,上面或下面,而是在正方形內。 這將導致紅色正方形內的數字0和藍色正方形內的數字1。 如何才能做到這一點?

ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +
geom_bar() +
theme(legend.position = "top", 
    legend.direction = "horizontal") +
guides(color = guide_legend(title.position = "left", label.position = "top")) 

由於你正在使用fill你需要在guides使用填充,然后使用label.vjusttitle.vjusttitle.vjust所有內容。

library(tidyverse)

ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +
  geom_bar() +
  theme(legend.position = "top", 
        legend.direction = "horizontal") +
  guides(fill = guide_legend(label.vjust = -7, label.position = "top", title.vjust = 0.2))

reprex包創建於2018-11-23(v0.2.1)

通過微調,您可以使用change-geom-texts-default-a-legend-to-label-string-their中顯示的方法。 這會更改鍵生成功能,因此允許ggplot2計算為您放置標簽的位置。

我的想法是保留原始rectGrobgeom_bar圖例鍵,並使用額外的textGrob將標簽放在頂部。

library(ggplot2)
library(grid)

oldK <- GeomBar$draw_key # to save for later

# see other answer on how to tweak function based n manual colours
GeomBar$draw_key <- function (data, params, size, 
                              var=unique(mtcars$vs),
                              cols=scales::hue_pal()(length(var))) {

    # match labels to the fill colour
    txt <- if(is.factor(var)) levels(var) else sort(var)
    txt <- txt[match(data$fill, cols)]

    # This is from the original GeomBar$draw_key -------------------
    lwd <- min(data$size, min(size)/4)
    rg <- rectGrob(width = unit(1, "npc") - unit(lwd, "mm"), height = unit(1, 
        "npc") - unit(lwd, "mm"), gp = gpar(col = data$colour, 
        fill = alpha(data$fill, data$alpha), lty = data$linetype, 
        lwd = lwd * .pt, linejoin = "mitre"))
    # ---------------------------------------------------------------

    # Add text label: lifted from other answer
    # hard-coded text size multiplier -- got to be a better way!
    tg <- textGrob(txt, 0.5, 0.5,  
             just="center", 
             gp = gpar(col = "black", 
                       fontfamily = data$family, 
                       fontface = data$fontface, 
                       fontsize = 10*data$size * .pt)) 
    # ---------------------------------------------------------------

    grobTree(rg, tg) # output new key
}

然后你可以繪圖

ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +
  geom_bar() +
  theme(
    legend.position = "top", 
    legend.direction = "horizontal",
    legend.text = element_blank())

# reset key function to original
GeomBar$draw_key <- oldK

在此輸入圖像描述

這應該相當穩健,以調整你的情節。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM