将ggplot图例标签直接放在其填充颜色上

时间:2018-11-24 00:38:23

标签: r ggplot2

对于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")) 

2 个答案:

答案 0 :(得分:4)

由于您使用的是fill,因此需要在guides内使用填充,然后使用label.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 package(v0.2.1)于2018-11-23创建

答案 1 :(得分:0)

稍作调整,您可以使用change-geom-texts-default-a-legend-to-label-string-itself中显示的方法。这会更改密钥生成功能,因此允许 class Parent extends React.Component { constructor(props){ super(props); this.state = { value: 0 } } componentDidMount() { document.addEventListener('keydown', () => { this.setState({value: this.state.value++}); }) } render() { return (<ChildComponent value={this.state.value} />) } } 计算出要为您放置标签的位置。

想法是保留ggplot2图例键的原始rectGrob并使用附加的geom_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
}

enter image description here

这对于调整图的大小应该非常强大。