How to plot a histogram with different colors in R

52,779

Solution 1

You need to add the col arguments in the hist method as follows:

t<- c(69,68,67,65,65,62,59,59,54)
hist(t, main="Distribution of Player Ratings",xlim = c(0,99), 
       breaks=c(seq(40,99,5)), col = c("blue", "red", "gray", "green"))

See the image I got after above execution:

enter image description here

Now you can replace the colour values(either name or hexadecimal values like "#FFFF00") as per your requirements.

Solution 2

In your earlier question, you had mentioned ggplot2, so here is a ggplot2 solution:

First simulate your dataset:

set.seed(123)
df <- data.frame(X = sample(50:89, 500, replace = T))

Add a new variable that defines your color criteria:

df$group = ifelse(df$X < 66, "50-65", ifelse(df$X < 75, "66-74", "75-89"))

Now, load the ggplot2 library to create a histogram

library(ggplot2)

ggplot(df, aes(X, fill = group)) + geom_histogram()

To give custom colors, use scale_fill_manual:

ggplot(df, aes(X, fill = group)) + geom_histogram() +
    scale_fill_manual(values = c("50-65" = "#CD7F32",
                                 "66-74" = "#C0C0C0",
                                 "75-89" = "gold"))

This is how the figure looks like now:

enter image description here

Although you included xlim = c(0,99) (which is not visible in the attached plot), I don't know why you would use that. If you wish you can add an xlim argument with + xlim(0,99).

To learn more about ggplot2, look here.

Note: You can define the number of bins or binwidth in geom_histogram. Refer this for more

Share:
52,779
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    I have a dataset of about 500 integer values in a csv file, with each value between 50-89. I am trying to create a histogram in R in which the bars that represent values 50-65 are bronze colored, 66-74 silver, and 75-89 gold. The script I have so far is the following:

    dat1 <- read.csv("test2.csv", header=F)$V1
    hist(dat1, main="Distribution of Player Ratings", xlim = c(0,99), breaks=c(seq(40,99,5)))
    

    A sample of test2.csv is shown below (extremely simple)

    69,
    68,
    67,
    65,
    65,
    62,
    59,
    59,
    54,
    

    Right now my graph is:

    My Graph

    What would I have to do in order to fulfill the color guidelines explained earlier?

    Note: I had posted this question earlier, but without any of my code or a reference to my dataset.