I have a histogram as shown in the picture. I want the bars in the two regions to be coloured red and green respectively, i.e., the bars from 0 to the first black border on the left should be coloured red and the bars in the second region should be coloured green. Can this be done in R? The code used to get the histogram is
hist(pr4$x[pr4$x[,1]>-2,1],breaks=100)
Since R 4.0.0 histograms are gray by default, not white. Now that you know how to create a histogram in R you can also customize it. Hence, if you want to change the bins color, you can set the col parameter to the color you prefer. As any other plots, you can customize lots of features of the graph, like the title, the axes, font size …
To visualize multiple groups separately we use the fill property of aesthetics function to color the plot by a categorical variable. df: determines the data frame to be plotted. x: determines the data variable. fill: determines the color of bars in the histogram.
Histogram Takes continuous variable and splits into intervals it is necessary to choose the correct bin width. The major difference between the bar chart and histogram is the former uses nominal data sets to plot while histogram plots the continuous data sets. R uses hist () function to create histograms.
Density plots help in the distribution of the shape. The following histogram in R displays the height as an examination on x-axis and density is plotted on the y-axis. That’s all about the histogram and precisely histogram is the easiest way to understand the data.
The best way to do this is to allow hist
to do the calculations for you but then use hist
(again) to do the actual plotting. Here's an example:
set.seed(1)
x <- rnorm(1000)
h <- hist(rnorm(1000), breaks=50, plot=FALSE)
cuts <- cut(h$breaks, c(-Inf,-.5,1.75,Inf))
plot(h, col=cuts)
The .5 and 1.75 in the last line are the threshold values where you want to have different colors.
Note: my original answer used barplot
, but that strategy makes the axes kind of difficult to work with.
Here's the result:
Here's the method I mentioned in comments:
Make some test data (you should do this in your question!)
test = runif(10000,-2,0)
get R to compute the histogram but not plot it:
h = hist(test, breaks=100,plot=FALSE)
Your histogram is divided into three parts:
ccat = cut(h$breaks, c(-Inf, -0.6, -0.4, Inf))
plot with this palette, implicit conversion of factor to number indexes the palette:
plot(h, col=c("white","green","red")[ccat])
ggplot2
solutions are also available.
Try this:
hist(pr4$x[pr4$x[,1]>-2,1],breaks=100, col = c(rep("white", 69), rep("green", 15), rep("red", 16)))
You might have to adjust the repeat number for each color depending on the number of breaks within the histogram.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With