Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change colors when using scale_fill_discrete in R?

I have the data below:

time=c(200,218,237,237,237,237,237,246,246,246,257,257,257,272,272,272,294,294,294)
location=c("A","A","D","C","A","B","B","D","C","B","D","C","B","D","C","B","D","C","B")
value=c(0,774,0,0,2178,0,2178,0,1494,2644,1326,1504,4188,3558,1385,5013,12860,829,3483)
dataA=data.frame(time,location,value)

and I made a graph.

ggplot(data=dataA, aes(x=time, y=value))+
  geom_area(aes(group=location, fill=location), position="stack", linetype=1, size=0.5 ,colour="black") +
  scale_fill_discrete(breaks=c("A","B","C","D"), labels=c("Main_town","B","C","D"))+
  theme_classic(base_size=18, base_family="serif")+
  theme(legend.position="right",
        axis.line=element_line(linewidth=0.5, colour="black"))+
windows(width=5.5, height=5)

I changed one of the legend label from A to main_town using scale_fill_discrete(). Then color is automatically generated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

I want to change this color according to my preference. When I add a code, scale_fill_manual(values=c("darkblue","darkred","khaki4","darkgreen"))+ the below message shows up and the graph is before I changed legend label.

Scale for fill is already present.
Adding another scale for fill, which will replace the existing scale.

enter image description here

How can I change colors when using scale_fill_discrete()? I want to change colors to "darkblue","darkred","khaki4","darkgreen"

Could you please let me know how to do that? Or do you let me know simply how to change legend labels maintaining colors I want?

Always many thanks!!!

>Solution :

I think you need scale_fill_discrete(type = c(...)).

library(ggplot2)

ggplot(data=dataA, aes(x=time, y=value))+
  geom_area(aes(group=location, fill=location), position="stack", linetype=1, size=0.5 ,colour="black") +
  scale_fill_discrete(breaks=c("A","B","C","D"), labels=c("Main_town","B","C","D"),
                      type=c("darkblue","darkred","khaki4","darkgreen"))+
  theme_classic(base_size=18, base_family="serif")+
  theme(legend.position="right",
        axis.line=element_line(linewidth=0.5, colour="black"))

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading