ggplot2 & ggpattern: How to specify legend columns/rows when fill and pattern are cobined?

32 Views Asked by At

In the following example, I use both pattern and fill. The legend has to be below the plot. How can force the legend in one row?

I can't get guides(fill=guide_legend(nrow=1)), as used here, to work.

see image

My Code:

library(ggplot2)
library(ggpattern)

g <- ggplot(mpg, aes(cty, hwy, group=trans, fill=trans, colour=trans))

g + geom_col_pattern( 
  aes(
    pattern_angle=trans),
  pattern_fill='black',                  
  pattern_colour=NA,
  pattern='stripe',
  position=position_dodge()) +  
  scale_pattern_angle_discrete(labels=c(1:10)
  )+
  scale_fill_discrete(labels=c(1:10)
  )+
  scale_colour_discrete(labels=c(1:10)
  )+
  theme(legend.position = "bottom") + 
  guides(colour = guide_legend(nrow = 1))+ 
  guides(fill = guide_legend(nrow = 1))+ 
  guides(pattern = guide_legend(nrow = 1))

1

There are 1 best solutions below

0
stefan On BEST ANSWER

You are mapping on the pattern_angle aes. Hence you have to set the number of rows for the pattern_angle guide instead of pattern.

library(ggplot2)
library(ggpattern)

g <- ggplot(mpg, aes(cty, hwy, group = trans, fill = trans, colour = trans))

g + geom_col_pattern(
  aes(
    pattern_angle = trans
  ),
  pattern_fill = "black",
  pattern_colour = NA,
  pattern = "stripe",
  position = position_dodge()
) +
  scale_pattern_angle_discrete(labels = c(1:10)) +
  scale_fill_discrete(labels = c(1:10)) +
  scale_colour_discrete(labels = c(1:10)) +
  theme(legend.position = "bottom") +
  guides(
    colour = guide_legend(nrow = 1),
    fill = guide_legend(nrow = 1),
    pattern_angle = guide_legend(nrow = 1)
  )