Reputation: 19
I want to adding a legend in my graph.
but It's very difficult to me.
so please help me..
library(ggplot2)
library(scales)
library(grid)
library(gcookbook)
data<-read.csv("maxmin.csv")
attach(data)
head(data)
str(data)
to<-ggplot(data,aes(x=obs,y=toaverage)) + geom_ribbon(aes(ymin=tomin,ymax=tomax),alpah=0.9,fill="grey50") + geom_line(colour="black")+ labs(x = "", y = "")+ scale_y_continuous(breaks=seq(0,70,10))+ expand_limits(max(data$tomax),y=c(0,70))
to<-to + theme(axis.text.x=element_blank())+ geom_ribbon(aes(ymin=tomax25,ymax=tomax75),alpah=0.9,fill="grey30") + theme(axis.ticks.x=element_blank())
to<- to + theme(line = element_blank())+ theme(text = element_text(size=15))
to<-to + geom_line(aes(y=toaverage),colour="black")
this is work.
and I want to adding a legend at bottom
to<-to+ scale_colour_manual(value=c("black","grey50",grey"30"), breaks=c("toaverage","tomax","tomax25"), labels=c("average","(max,min)","(25%,75%)"))+ theme(legend.position="bottom")
But this is not work..
(tomax25 and tomax75 is quantile of max and min)
actually I want to adding a average line and grey50 and grey 30 are colour box.
How i can solve this problem.?
Thanks in advinance.
Upvotes: 0
Views: 265
Reputation: 59355
So this should get you started.
# create sample dataset - you should provide this!!!
x <- 1:10
set.seed(1) # for reproducibble example
df <- data.frame(x,y=rnorm(100,mean=sample(x,10)))
gg <- aggregate(y~x,df,fivenum)
gg <- with(gg,data.frame(x,gg[,2]))
colnames(gg) <- c("x","tomin","tomax25","toaverage","tomax75","tomax")
# you start here, more or less...
library(ggplot2)
ggplot(gg,aes(x=x))+
geom_ribbon(aes(ymin=tomin,ymax=tomax,fill="Full.Range"),alpha=0.9)+
geom_ribbon(aes(ymin=tomax25,ymax=tomax75,fill="IQR"),alpha=0.9)+
geom_line(aes(y=toaverage,color="Mean"))+
scale_color_manual(name="",values=c(Mean="orange"),guide=guide_legend(order=1))+
scale_fill_manual(name="",values=c(Full.Range="grey70",IQR="grey30"),
breaks=c("Mean","IQR","Full.Range"))
The point in my comment, and in the referenced post, is that to get a legend you have to create an aesthetic mapping. You do this by putting hte reference to the color/fill inside the call to aes(...)
. Then you can use scale_fill_manual(...)
to set the fill colors by setting values=...
to a named vector of colors, as shown above.
Upvotes: 1