棒和线图在一个图与下GGPLOT2图例(bar and line plot in one chart

2019-06-27 22:33发布

我想提出一个酒吧和两个独立但相关的系列相同的图上的线图与传说(酒吧情节的季度增长的线图是每年增长)。

我目前在宽幅和代码这样的data.frame做到这一点:

p <- ggplot() +
    geom_bar(df, aes(x=Date, y=quarterly), colour='blue') +
    geom_line(df, aes(x=Date, y=annual), colour='red')

但我不能工作了如何添加一个传奇,其上有标注为“年度增长”红线; 和一个蓝色的方形标记“每季度增长”。

另外,我无法工作,如何针对不同系列的长形data.frame不同的充geoms。

更新:

下面的示例代码让我的争取解决方式的一部分,而是一个真正丑陋的重复传奇。 还在寻找一个完整的解决方案...这方法是基于将在长表中的数据,然后绘制数据子集...

library(ggplot2)
library(reshape)
library(plyr)
library(scales)

### --- make a fake data set
x <- rep(as.Date('2012-01-01'), 24) + (1:24)*30
ybar <- 1:24
yline <- ybar + 1

df <- data.frame(x=x, ybar=ybar, yline=yline)
molten <- melt(df, id.vars='x', measure.vars=c('ybar', 'yline'))
molten$line <- ifelse(molten$variable=='yline', TRUE, FALSE)
molten$bar <- ifelse(molten$variable=='ybar', TRUE, FALSE)

### --- subset the data set
df.line  <- subset(molten, line==TRUE)
df.bar   <- subset(molten, bar==TRUE)

### --- plot it
p <- ggplot() +
geom_bar(data=df.bar, mapping=aes(x=x, y=value, fill=variable, colour=variable),
    stat='identity', position='dodge') +
geom_line(data=df.line, mapping=aes(x=x, y=value, colour=variable)) +

opts(title="Test Plot", legend.position="right") 

ggsave(p, width=5, height=3, filename='plot.png', dpi=150)

并举例情节...

Answer 1:

通过使用的subset参数geoms。

> x=1:10;df=data.frame(x=x,y=x+1,z=x+2)
> ggplot(melt(df),
    aes(x,value,color=variable,fill=variable))+
  geom_bar(subset=.(variable=="y"),stat="identity")+
  geom_line(subset=.(variable=="z"))



文章来源: bar and line plot in one chart with a legend under ggplot2
标签: r ggplot2