如何减少ggplot2中条形图的图例符号厚度

时间:2019-05-21 09:04:16

标签: r ggplot2 legend

被要求减小ggplot2中条形图的图例符号的厚度(需要使它们太薄以至于它们看起来像窄的水平线)。这是我的情况的简化:

library(ggplot2)

# Simple bar chart example
g <- ggplot(mpg, aes(class)) +
  geom_bar(aes(fill = drv))
g

# Failed attempt to reduce the thickness of the legend symbol using guides(). 
# I also tried negative values, but that gives errors. 
# However, increasing the size works well. I need the symbols very thin.
g2 <- g + guides(fill = guide_legend(override.aes = list(size = 0.1)))
g2

# Also adjusting with some theme options is not really working for me
# nor what I really need because is also reducing the distance between the labels.
g + theme(legend.key.height = unit(0.1, "mm"))

也许除了利用grid软件包的功能来编辑图例自身而已,或者像Inkscape(?)这样在R之外进行操作之外,别无选择。

reprex package(v0.2.1)于2019-05-21创建

2 个答案:

答案 0 :(得分:1)

一种解决方案是更改图例形状。此解决方案并不完美(太复杂),因为您必须添加geom_point层以更改其形状。

library(ggplot2)
ggplot(mpg, aes(class, fill = drv)) +
  # Remove legend for bar
  geom_bar(show.legend = FALSE) +
  # Add points to a plot, but invisible as size is 0
  # Shape 95 is a thin horizontal line
  geom_point(aes(y = 0, color = drv), size = 0, shape = 95) +
  # Reset size for points from 0 to X
  guides(fill = guide_legend(override.aes = list(size = 10)))

enter image description here


另一种解决方案是添加geom_line层(即,线条是细线):

library(ggplot2)
ggplot(mpg, aes(class, fill = drv)) +
  geom_bar(show.legend = FALSE) +
  geom_line(aes(y = NA, color = drv), size = 2)

enter image description here

答案 1 :(得分:1)

最后,我利用@PoGibas的creative solution添加了geom_line,然后手动编辑了guides。由于color美学被另一种语言所使用,因此我不得不使用其他可用的美学,并且linetype是一个很好的候选人。我接受了@PoGibas的回答,但希望下面的代码能增加解决方案的多样性:

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 3.5.3
library(scales)  # just for getting the default colors

ggplot(mpg, aes(x = class)) +
  geom_bar(aes(fill = drv),
           show.legend = FALSE)+
  geom_line(aes(y = 0, # y must be provided, so force it to 0 (if forced to NA, it appears in the OY axis)
                linetype = drv)) + # can be any unused aesthetic 
  guides(linetype = guide_legend(override.aes = list(linetype = "solid",
                                                     color = scales::hue_pal()(3),
                                                     size = 1)))

因此,如果我们也“强制”使用alpha美学,然后根据需要编辑guides,则可以应用相同的原理。

  ggplot(mpg, aes(x = class)) +
    geom_bar(aes(fill = drv),
             show.legend = FALSE)+
    geom_line(aes(y = 0,
                  alpha = drv)) +
    guides(alpha = guide_legend(override.aes = list(alpha = 1, # 1 is recycled 3 times here, as size is below as well
                                                    color = scales::hue_pal()(3),
                                                    size = 2)))
#> Warning: Using alpha for a discrete variable is not advised.

reprex package(v0.2.1)于2019-05-21创建