0

How do I color two data series different colors on the same plot?

I combined two different dataframes:

ages_test=c('<18','18-24','25-44','45-64','65+',"UNKNOWN")

values_test=c(411694,1313082,2301521,918416,41728,178)
df_test1=data.frame(ages_test,values_test)

values_test=c(134924,350794,612476,228237,10472,49)
df_test2=data.frame(ages_test,values_test)

df_combined = rbind(df_test1, df_test2)

enter image description here

Then I created this plot:

df_combined %>%
  ggplot(aes(x=ages_test, y=values_test), label=values_test) +
  geom_bar(stat='identity') +
  scale_y_continuous(breaks=scales::breaks_extended(n=10), labels=comma) +
  geom_text(hjust=.5, vjust=-1, size=3, aes(label=comma(values_test)))

enter image description here

This chart contains the two different data series and labels for each. I want one of them to be a different color so that I can differentiate between the two.

I tried adding fill=values_test to aes like so ggplot(aes(x=ages_test, y=values_test, label=values_test, fill=values_test)) but the resulting chart shows a color gradient:

enter image description here

However, I want only two different colors, one for each data series.

I've also tried using color=as.factor(values_test) but this yields 12 different colors, one for each age category in my combined dataframe.

1 Answer 1

3

Use dplyr::bind_rows to combine the two dataframe with unique ids. You can then use fill in aes to give them different colors.

library(ggplot2)
df_combined = dplyr::bind_rows(df_test1, df_test2, .id = 'id')

ggplot(df_combined, 
      aes(x=ages_test, y=values_test, fill = id), label=values_test) +
  geom_bar(stat='identity') +
  scale_y_continuous(breaks= scales::breaks_extended(n=10), 
                     labels=scales::comma) +
  geom_text(hjust=.5, vjust=-1, size=3, aes(label=scales::comma(values_test)))

enter image description here

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks again! You helped me out yesterday as well: stackoverflow.com/questions/64796835/…
How do I customize the colors? I tried adding the following + scale_color_manual(values=c('dark green','green')) but it didn't work.
Use scale_fill_manual : scale_fill_manual(values = c('dark green','green'))
What resources did you use to learn R? I started about a week ago and I'm using different pieces of code to hack things together. It's not very efficient.
Lot of practice coding and lurking on stackoverflow has helped me learn R.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.