使用geom_col和geom_line格式化ggplot

时间:2018-04-10 15:39:36

标签: r ggplot2 legend

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

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

包含错误图例的图表 graph with incorrect legend

1 个答案:

答案 0 :(得分:0)

fill的地图geom_col(或geom_area,看起来相同):

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

enter image description here