0
votes

I wish to plot multiple model data in lines with customized color for each line using ggplot2 library functions. Am able to do so with random colors generated by ggplot but if I try to put customized colors, the legend is disappearing. Please help me with this issue. Below is the reproducible example where I want one black and one green color line along with labels. Thanks in advance.

library(ggplot2)

flux<-c(-4.351645e-11 ,7.724330e-10 ,-1.631623e-10,2.832141e-10,-2.396649e-11,
# first model 5 entries
-7.825169e-10 ,-2.534337e-10,-3.837198e-10 ,-2.765284e-10,-6.515152e-10)
# 2nd model 5 entries

model<-c('SDGVM','SDGVM','SDGVM','SDGVM','SDGVM',  # 1st model
        'TRIFFID','TRIFFID','TRIFFID','TRIFFID','TRIFFID') # 2nd model

latitude<-c(-34,-36,-39,-41,-44,-34,-36,-39,-41,-44)

color<-c('black','black','black','black','black',
            'green','green','green','green','green')

input_df <-structure(list(flux = flux, model = model, lat = latitude,
color_plate=color), 
.Names = c("flux","model", "lat","color_assigned"), row.names = c(NA, -10L),
class = "data.frame") 

xlims=c(-50,-30) # x axis extent
custom_break<-seq(min(xlims),max(xlims),by=2)


theme_set(theme_bw(12))

chart <-ggplot(input_df, aes(x=lat, group=model, colour=model, fill=model)) +
     geom_line(aes(y=flux), size=1.0) +
    theme(legend.position='bottom') + 
        scale_x_continuous('Latitude',limits=xlims,breaks=custom_break) + 
#custom breaks_to customize labels in x axis
    scale_y_continuous(expression('Flux Difference')) +
    scale_colour_discrete(name='', guide=guide_legend(nrow=4)) +
    scale_fill_discrete(name='Model') +
    geom_hline(aes(yintercept=0)) #to add black line at 0
print(chart)
1
(-1) Please format your post.Arun
@Arun - your friendly neighbourhood helper is here to help.thelatemail
@thelatemail, glad, but I think you should've let the OP do it. It was such a badly formatted post!! Time to make some effort into questions.Arun
@Arun - it just bugged me so, I couldn't leave it as it was!thelatemail
@thelatemail, I totally understand the feeling.Arun

1 Answers

3
votes

You're setting the wrong property/attribute. You want to provide manual colours which can be set using scale_colour_manual.

Replace this line:

scale_colour_discrete(name='', guide=guide_legend(nrow=4)) +

with:

scale_colour_manual(values=c("black", "green"), name="", 
              guide=guide_legend(nrow=4)) +

and try again.

You should get a plot like this:

enter image description here

Does this help?