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 colour grouped barplot by group, not by conditon in ggplot?

I have a simple dataframe and would like to create a grouped barplot with x axis as "decade" and y as "rate" and separate bars for "condition", but with different colours for different decades.

df <- data.frame (decade  = c("1970", "1970","1980", "1980","1990","1990","2000","2000"),
              condition = c("Yes", "No", "Yes","No","Yes","No","Yes","No"),
              rate = c(60,34,50,25,24,12,9,5))

I have tried the following but it gives color based on fill conitions, the color for the decade does not display

ggplot(df,aes(y=rate,x=decade,fill=condition,color=decade))+
geom_bar(position="dodge",stat="identity")

enter image description here

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

What I would like is something like this, is this possible in ggplot or other graphical packages in R?

enter image description here

>Solution :

If you use just change the fill option to decade, it should do the trick.

library(tidyverse)

df <- data.frame (decade  = c("1970", "1970","1980", "1980","1990","1990","2000","2000"),
                  condition = c("Yes", "No", "Yes","No","Yes","No","Yes","No"),
                  rate = c(60,34,50,25,24,12,9,5))

ggplot(df,aes(y=rate,x=decade,fill=decade,color=condition))+
  geom_bar(position="dodge",stat="identity")
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