Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horizontal legend with title on top in ggplot

Tags:

r

ggplot2

I am trying to put the title of the legend on top, whereas the values are distributed horizontally but I cannot. Any hints will be very appreciated.

The code below provides the graph below, but I don't have space on my graph so I need something like this:

Sex

Female Male

df1 <- data.frame(
  sex = factor(c("Female","Female","Male","Male")),
  time = factor(c("Lunch","Dinner","Lunch","Dinner"), levels=c("Lunch","Dinner")),
  total_bill = c(13.53, 16.81, 16.24, 17.42))

 lp1 <- ggplot(data=df1, 
          aes(x=time, y=total_bill, group=sex, shape=sex, colour=sex)) + 
  geom_line() + 
  geom_point() +
  theme_bw() +
  theme(
   legend.direction = "horizontal",
   ) +     
  scale_color_manual(values=c("#0000CC", "#CC0000"),
                     name = 'Gender') 
    lp1

enter image description here

like image 835
Pulse Avatar asked Nov 05 '17 22:11

Pulse


People also ask

How to create horizontal legend using Ggplot2 in R?

How to create horizontal legend using ggplot2 in R? How to create horizontal legend using ggplot2 in R? The default legend direction is vertical but it can be changed to horizontal as well and for this purpose we can use legend.direction argument of theme function of ggplot2 package.

How to reverse the Order of the legend items in ggplot2?

The easy way to reverse the order of legend items is to use the ggplot2 legend guides () function. It change the legend order for the specified aesthetic (fill, color, linetype, shape, size, etc).

How to change plot titles in ggplot2?

Change plot titles by using the functions ggtitle (), xlab () and ylab () : p + ggtitle("Plot of length n by dose") + xlab("Dose (mg)") + ylab("Teeth length") Note that, you can use n to split long title into multiple lines. Change plot titles using the function labs () as follow :

How to place the legend on the bottom of the plot?

And here’s how to place the legend on the bottom of the plot: library (ggplot2) ggplot(iris, aes (x=Sepal.Length, y=Sepal.Width, color=Species)) + geom_point() + theme(legend.position = "bottom ") Example: Place Legend On Inside of Plot. You can also specify the exact (x, y) coordinates to place the legend on the inside of the plot.


1 Answers

Try this:

cols <- c("#0000CC", "#CC0000")

df1 %>%
  ggplot(aes(time, total_bill, group = sex, shape = sex, colour = sex)) +
  geom_line() +
  geom_point() +
  theme_bw() +
  scale_shape(
    guide = guide_legend(
      direction = "horizontal",
      title.position = "top"
    )
  ) +
  scale_color_manual(
    values = cols,
    name = "Gender",
    guide = guide_legend(
      direction = "horizontal",
      title.position = "top"
    )
  )

enter image description here

like image 76
tyluRp Avatar answered Oct 04 '22 02:10

tyluRp