简体   繁体   中英

How to plot a histogram with different colors in R

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:

我的图表

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.

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:

在此处输入图片说明

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

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:

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM