ggplot 图例条和同一图中的线

ggplot Legend Bar and Line in Same Graph

我在同一张图表上绘制条形图和折线图,我想知道是否有办法让 ggplot 的图例说条形图代表一件事,而线代表一件事其他。也就是说,与其确定他们填写的内容,这是我知道该怎么做的,不如说 "line = tomatoes"、"bar = potatoes".

数据:

x <- c(0:10)
y1 <- c(0,.5,1,1.5,2,2.5,3,3.5,4,4.5,5)
y2 <- append(c(1:5),c(6,8,10,12,14,16))
mydata <- as.data.frame(cbind(x,y1,y2))
x=c(0:10)

见下面的代码。您需要具有美学映射才能显示图例。看到这个的任何其他人都可以随意提出一种在单个图例上执行此操作的方法,以摆脱两者之间看起来有些丑陋的 space。

y1=c(0,.5,1,1.5,2,2.5,3,3.5,4,4.5,5)
y2=append(c(1:5),c(6,8,10,12,14,16))
mydata1=data.frame(x=x,line=y2,Type="Line")
mydata2=data.frame(x=x,bar=y1,Type="Bar")

ggplot(data=mydata1) + geom_line(aes(x=x,y=line,linetype=Type)) +
  geom_bar(data=mydata2,aes(x=x,y=bar,fill=Type),stat="identity") +
  scale_fill_manual(values=c("black","black")) +
  guides(fill = guide_legend(override.aes=list(fill=c("black")))) +
  labs(fill="", linetype="")