Home > Back-end >  How to change colour for barplot in ggplot2 using viridis package?
How to change colour for barplot in ggplot2 using viridis package?

Time:10-05

enter image description hereI am trying to make a ggplot with the viridis package (magma option) for colouring the bars. I keep going to the default colour option.

here is my code:

library(ggplot2)
library(viridis)
barplotforraredisease <- data. frame(family = c(" Singleton", "Family of 2", "Family of 3", "Family of 4", "Family of 5"), total members=c(108,52,121,9,2))

p <- ggplot (data=barplotforraredisease, aes (x=family, y=total members)) geom bar(stat = "identity")  geomtext(aes (label=total members), vjust= -0.3, size = 3.5)  theme_minimal()  ggtitle( "Number of families tested") scale color viridis(discrete = TRUE, option = "viridis")

I've attached a screenshot of what my plot looks like, I would appreciate any help.

CodePudding user response:

The code you posted has some underscores replaced with spaces.

Once that is fixed, this should work. Note that you need to set the fill value to the column that you want, change scale_color_viridis() to scale_fill_viridis() and set option = "magma".

ggplot(
    data=barplotforraredisease, aes(
        x=family, y=total_members, fill=family)
    )   
    geom_bar(stat = "identity")   
    geom_text(aes(label=total_members), vjust= -0.3, size = 3.5)  
    theme_minimal()   
    ggtitle( "Number of families tested")   
    scale_fill_viridis(discrete = TRUE, option = "magma")

enter image description here

Data:

barplotforraredisease  <- structure(list(family = c(" Singleton", "Family of 2", "Family of 3",
"Family of 4", "Family of 5"), total_members = c(108, 52, 121,
9, 2)), class = "data.frame", row.names = c(NA, -5L))
  • Related