Scale_color_manual not working as expected

2019-03-03 09:08发布

问题:

I am using the following piece of code to create a bar graph:

temp1 <- melt(final,id='Time')
p <- ggplot(temp1, aes(x=Time, y=value, fill=variable)) +
  geom_bar(stat="identity", position = "fill") +
  scale_y_continuous(labels = percent_format()) +
  ggtitle('Cost Structure Breakdown') + theme_bw() + ylab('Percent Spread') +
  theme(panel.grid.minor.x = element_blank(),
        panel.grid.minor.y = element_blank(),
        panel.grid.major.x=element_line(color='grey90',linetype='dashed'),
        panel.grid.major.y=element_line(color='grey90',linetype='dashed'),
        plot.title=element_text(size=20),
        axis.text=element_text(size=15),
        legend.text=element_text(size=15),
        legend.key=element_blank(),
        legend.title=element_blank()) +
  scale_color_manual(values=c("#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6"))
p

The presence of scale_color_manual doesn't seem to have any affect on the resulting plot, it stays the same even if I remove scale_color_manual. My dataframe final has 10 variables and I am using melt on Time. Therefore, I have used 9 colors for the plot. The dataset itself can be found here.

Any help on this would be much appreciated.

回答1:

There is no reproducible data. I, therefore, created a simple data here. I also simplified the code of the OP. What is necessary here is scale_fill_manual.

mydf <- data.frame(time = letters[1:3],
                   variable = LETTERS[1:3],
                   value = runif(3, 10, 15),
                   stringsAsFactors = FALSE)


ggplot(mydf, aes(x=time, y=value, fill=variable)) +
  geom_bar(stat="identity") +
  scale_fill_manual(values=c("#a6cee3","#1f78b4","#b2df8a"))