简体   繁体   English

标题在ggplot顶部的水平图例

[英]Horizontal legend with title on top in ggplot

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

在此输入图像描述

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"
    )
  )

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM