Как уменьшить толщину символа легенды для гистограммы в ggplot2 - PullRequest
0 голосов
/ 21 мая 2019

Попросили уменьшить толщину символа легенды для гистограммы в 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 или сделать это вне R, как Inkscape (?).

Создано в 2019-05-21 с помощью представительного пакета (v0.2.1)

Ответы [ 2 ]

1 голос
/ 21 мая 2019

Наконец, я использовал креативное решение @PoGibas, чтобы добавить 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.

Создано в 2019-05-21 представьте пакет (v0.2.1)

1 голос
/ 21 мая 2019

Одним из решений является изменение формы легенды. Это решение не является идеальным (слишком сложным), так как вам нужно добавить слой 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

...