1

I am creating a facet barplot with different colors representing different ranges of values. I want to add a legend to the graph to show the ranges and their corresponding colors, but the scale_fill_manual does not work. How to correct this problem? Really appreciate your help.

The codes are as below :

set.seed(123)
n= 15*24 + 3
dt <- data.table(t=1:n)
dt[, y := abs(sin(2*pi*t/25.4)) + rnorm(n,1,0.2)]

dt[,t_in_day := t%%24]
dt[,day := floor(t/24)]
dt2 <- copy(dt)
dt2[,day := day-1]

dt2[,t_in_day := t_in_day + 24]
dt <- dt[day<max(day)]
dd <- rbind(dt, dt2)
dd <- dd[day>-1]

dd[, day_str := sprintf("day\n%03d",(day+1))]

col1<-c()

break1=10
rbPal <- colorRampPalette(c('red','yellow'))
col1 <- rbPal(break1)[as.numeric(cut(dd[,y],breaks = break1))]

cuts<-levels(cut(dd[,y],breaks = break1))
cuts<-gsub(","," - ",cuts)
cuts<-gsub("\\(","[",cuts)

ggplot(dd,aes(x=t_in_day,y=dd[,y]),fill=cuts) +
geom_bar(stat="identity",fill=col1) + 
facet_grid(day_str ~ .) + scale_x_continuous(name="time (h)",breaks = 0:8 * 6)+
scale_y_continuous(name="y")+
scale_fill_manual(values=rbPal(break1),labels=cuts)
Elizabeth
  • 39
  • 2
  • Possible duplicate of [Change bar plot colour in geom\_bar with ggplot2 in r](https://stackoverflow.com/questions/38788357/change-bar-plot-colour-in-geom-bar-with-ggplot2-in-r) – Michael Harper Apr 05 '18 at 09:10

1 Answers1

1

make sure fill appears within the aes function. Try

ggplot(dd,aes(x=t_in_day,y=dd[,y],fill=cuts)) + 
  ...
Melissa Key
  • 4,476
  • 12
  • 21
  • I figured out. Changing geom_bar(stat="identity",fill=col1) to geom_bar(stat="identity",aes(fill=col1)) helps. Thank you very much. :-) – Elizabeth Apr 05 '18 at 14:48