【问题标题】:Legend formatting for ggplot with geom_col and geom_line带有 geom_col 和 geom_line 的 ggplot 的图例格式
【发布时间】:2018-04-10 15:39:36
【问题描述】:

我正在尝试执行以下代码来获得一个图例,其中“容量”有一条红线,“需求”有一个黑框,而不是图像中的图例,“容量”有一个带有红色轮廓的黑框

ggplot(df, aes(x,y2)) + 
  geom_line(aes(x,y2,colour = "Capacity")) + 
  geom_col(aes(x,y1,colour="Demand"), fill = "black") + 
  theme(axis.ticks.x = element_blank(), axis.text.x = element_blank(), plot.title = element_text(face = "bold", hjust = 0.5)) + 
  labs(title = paste("Optimal Schedule", check[[4]], "-", check[[5]], sep = " "), x = "Time (hours)", y = "Driver Hours") + 
  ylim(0,max(df$y3)) + 
  scale_colour_manual("", values = c("red", "black"), guide = guide_legend(override.aes = list(linetype = c("solid","blank")), shape = c(NA,NA)))

图例不正确

【问题讨论】:

  • 为什么不geom_line(aes(x,y2,colour = "Capacity")) geom_col(aes(x,y1, fill="Demand"))
  • 你可以使用scale_fill_manual(values = c(Capactity = NA, Demand = "black")
  • 我认为你应该在这里使用geom_area 而不是geom_col
  • 有趣的是,我最终在这里绘制了完全相同的变量图!

标签: r ggplot2 legend


【解决方案1】:

geom_col(或geom_area,看起来一样)映射fill

library(ggplot2)
df <- data.frame(Capacity = cumsum(rnorm(1000)))
df$Time <- 1:nrow(df)
df$Demand <- df$Capacity * 0.8

ggplot(df, aes(x = Time)) + 
  geom_line(aes(y = Capacity,colour = "Capacity")) + 
  geom_col(aes(y = Demand, fill = "Demand"))  +
  scale_colour_manual("", values = c("red")) +
  scale_fill_manual(values = c("black"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    • 2021-08-10
    • 1970-01-01
    • 2022-06-22
    • 2020-07-26
    • 1970-01-01
    • 2011-05-12
    相关资源
    最近更新 更多