Color in ggplot - continuous value applied to a discrete variable

I already saw another question on this topic, but I still canโ€™t change my colors on my grouped panel in ggplot. This gives me a scale of blue, but I need green. I am very new to ggplot and will probably miss something obvious.

Here is my code:

TCplot=ggplot(mTCdf,aes(x=types4,y=TCs,group=years3,color=years3)) +geom_bar(aes(fill=years3),stat="identity",position="dodge",color="black") mTCdf$types4=factor(mTCdf$types4,levels=c("Single Year Lease","Multi-Year Lease","Permanent")) levels(mTCdf$types4) ###just to get my labels in my desired order TCplot=TCplot+ggtitle("Total Costs by Transaction_Type") +theme(plot.title=element_text(lineheight=.7,face="bold")) +xlab("Transaction Type") +ylab("Costs ($)") library(scales) TCplot=TCplot+scale_y_continuous(labels=comma) TCplot=TCplot+scale_fill_manual(values=c("#66FF22","#33FF22","#33EE22","#33DD22","#33CC22","#33BB22","#33AA22","#339922","#338822","#337722","#336622")) TCplot=TCplot+scale_fill_manual(values=c("#66FF22","#33FF22","#33EE22","#33DD22","#33CC22","#33BB22","#33AA22","#339922","#338822","#337722","#336622")) 

Error: Continuous value delivered on a discrete scale !!! Argh!

*** Can someone please help me apply a green gradient to this? Thanks!!

+4
source share
2 answers

You want to use scale_fill_gradient. Below is a brief example with some compiled data.

  t=data.frame(c1=c('a','a','b','b'),c2=c(1,0,1,0),c3=c(10,20,30,40)) ggplot(t,aes(x=c1,y=c3,group=c2,fill=c2))+geom_bar(stat="identity")+scale_fill_gradient(low="green",high="darkgreen") 
+8
source

The problem is that you treat your years3 column as if it were a discrete (categorical) variable when R thinks it is continuous (numeric). @JPC's solution fixes your problem, but I suggest you better fix the underlying problem. This can be done by changing the years3 column by a factor:

 mTCdf$years3 <- as.factor(mTCdf$years3) 

and then create the plot as you did.

+12
source

Source: https://habr.com/ru/post/1497874/


All Articles