It hard to answer without actual data but here some ideas to start with.
Made some sample data consisting of x
values, temp
values for lines and id
values used to color bar.
set.seed(1)
df<-data.frame(x=1:100,temp=runif(100,10,50),id=sample(1:3,100,replace=TRUE))
One solution is to use geom_tile()
and set y
values to 0 and use id for the fill=
. Problem with this solution is that height of bar will depend on range of your data. You can increase the height by calling several geom_tile()
calls with different y values.
ggplot(df,aes(x))+geom_line(aes(y=temp))+
geom_tile(aes(y=0,fill=factor(id)))
Another possibility is to use geom_bar()
with stat="identity"
and set y
value height of bars you need. With argument width=
you can change width of bars to ensure that there is no space between bars.
ggplot(df,aes(x))+geom_line(aes(y=temp))+
geom_bar(aes(y=4,fill=factor(id)),stat="identity",width=1)
UPDATE - solution with OP data
Data provided in question.
df<-read.table(text="datetime,temp_int,hum_int,dpv
2014-02-15 00:00:00,67.2,13.6,red
2014-02-15 00:15:00,63.4,13.8,yellow
2014-02-15 00:30:00,61.2,14.2,green
2014-02-15 00:45:00,60.4,14.5,green",header=T,sep=",")
Converting datetime column to POSIXct.
df$datetime <- as.POSIXct(df$datetime)
Melting data frame to long format.
library(reshape2)
df.melt<-melt(df,id.vars=c("datetime","dpv"))
Now for plotting use melted data frame. Argument colour=
should be placed inside the aes()
of geom_line()
because color change border of bars if placed inside the ggplot()
call. For geom_bar()
use dpv
as fill=
and also use scale_fill_identity()
because dpv
contains actual color names. If you need to have bars that are close to each other use width=900
. I set 900 because you have time interval of 15 minutes that correspond to 900 seconds (1 second is unit in this case).
ggplot(df.melt, aes(x = datetime, y = value)) +
geom_line(aes(colour = variable),size=1.9) +
geom_bar(aes(y=4,fill=dpv),stat="identity",width=900)+
scale_fill_identity()