R ggplot: «перекрестный эффект» в легенде (не исчезает с show.legend = NA) - PullRequest
4 голосов
/ 12 июня 2019

Следующий код вызывает нежелательный перекрестный эффект в легенде.

ggplot() + 
  geom_vline(aes(xintercept=1,colour="vertical"), show.legend = NA) +
  geom_hline(aes(yintercept=1,colour="horizontal"), show.legend = NA)

enter image description here

Я прочитал несколько постов, в которых говорится, что добавление show.legend = NAможет заставить этот эффект исчезнуть, но в моем случае это не сработает.

Редактировать: Чтобы избежать путаницы, я не хочу, чтобы легенда ушла!Я просто хочу, чтобы "крест" в легенде исчез, поэтому на нем должны отображаться такие элементы, как:

enter image description here

и

enter image description here

Ответы [ 3 ]

2 голосов
/ 12 июня 2019

Я согласен, что исправление легенд может быть сложным. Для этого примера просто введите show.legend = FALSE для ОДНОЙ строки, которую вы не хотите.

library(ggplot2)

ggplot() + 
  geom_vline(aes(xintercept=1,colour="vertical"), show.legend = F) +
  geom_hline(aes(yintercept=1,colour="horizontal"))

Хорошо, вот попытка 2. Это довольно уродливо; это втиснет две легенды в один сюжет. Это выглядит довольно близко к тому, что вы хотите.

library(ggplot2)

p1 <- ggplot() + 
  geom_vline(aes(xintercept=1,colour="vertical"))+
  scale_color_manual(values = "#619CFF")

p2 <- ggplot()+
  geom_hline(aes(yintercept=1,colour="horizontal"))

l1 <- cowplot::get_legend(p1)
l2 <- cowplot::get_legend(p2)

p3 <- ggplot() + 
  geom_vline(aes(xintercept=1,colour="vertical")) +
  geom_hline(aes(yintercept=1,colour="horizontal"))+
  theme(legend.position = "none")

l3 <- cowplot::plot_grid(l1, l2, ncol = 1, align = "v")
cowplot::plot_grid(p3, l3, nrow = 1, align = "h", rel_widths = c(1, 0.2))

2 голосов
/ 12 июня 2019

Если вы хотите немного покопаться в базовой сетке (что всегда весело), ​​вы можете вручную удалить вертикальную / горизонтальную полосу в направляющей.

library(ggplot2)
library(grid)
library(gtable)

p <- ggplot() + 
   geom_vline(aes(xintercept = 1, color = "vertical")) + 
   geom_hline(aes(yintercept = 1, color = "horizontal"))

## First we create a gr(aphical)ob(ject) from the ggplot
g <- ggplotGrob(p)

## then we have to find out which child grob represents the legend
## the grob with the name "guide-box" is the one we are looking for
guide <- which(g$layout$name == "guide-box")

## the legend consists of guides and the background, go for the guides
guide_lines <- which(g$grobs[[guide]]$layout$name == "guides")

## the guides contain a lot of different grobs
## if you look at g$grobs[[guide]]$grobs[[guide_lines]] you will see
## 4 segments representing the 4 lines, these are at position 4-5 and 7-8
## segments at 4 and 7 are the vertical lines and 5 and 8 the horizontal lines
## NOTE: this you have to find out "manually", if you change the order in your
##       ggplot the positions will be exactly switched
##       one could write e function which checks whether a line is horizontal
##       or vertical but this is most likely an overkill if this is for a 
##       single plot

## we can use gtable_filter to remove the unwanted lines
## it requires a regular expression formed by the names of the grobs to filter out
remove_pattern <- paste(g$grobs[[guide]]$grobs[[guide_lines]]$layout$name[c(4, 8)],
    collapse = "|")

## write back the filtered gtable
g$grobs[[guide]]$grobs[[guide_lines]] <- 
   gtable_filter(g$grobs[[guide]]$grobs[[guide_lines]],
                 remove_pattern, 
                 invert = TRUE)

## draw the grid
grid.draw(g)

Crossline removed

1 голос
/ 12 июня 2019

Кажется, есть известная ошибка с geom_vline https://github.com/tidyverse/ggplot2/issues/1267

С этим кодом на этом URL я вдохновился, придумав что-то, используя geom_linerange

thresholds <- data.frame(colour = "vertical", x = 1, ymin = 0.950, ymax = 1.050) 
ggplot() + 
  geom_hline(aes(yintercept = 1, colour = "horizontal"), show.legend = NA) +
  geom_linerange(data = thresholds, 
                 mapping = aes(x = x, ymin = ymin, ymax = ymax, linetype = colour)) +
  theme(legend.title = element_blank())

получая следующий участок

enter image description here

...