This page describes how to draw barplots with R and the ggplot2 library.

Let’s start with the most basic barchart ever. We apply the method on the mtcars dataset which is native with R, using geom_bar().

Note that we apply this geom on a single discrete variable. By default ggplot2 counts the occurence of each level and plots it.

 

 

 

 

 

If you want to plot the relationship between a continuous variable and a discrete variable, you need to specify stat=”identity” when calling the barplot:

 

 

Now, let’s change the color of the bars. There are 5 main ways to do so, all presented above and explained in the code below.

The 3 last examples show you how to: 1/ Remove the legend and add axis names 2/ Make a horizontal barplot with ggplot2 3/ Custom bar width


Not what you are looking for ? Make a new search !

[mediatagger]


3
Leave a Reply

avatar
2 Comment threads
1 Thread replies
2 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
DrorAzis Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Dror
Guest
Dror

Any easy way to color the bars in Red-Yellow-Green scale based on the value?
Any bar lower than 0.5 should be Red, any bar higher than 0.90 should be green and the values between shoud have a color scale from red to yellow to green (let’s say with 0.7 as the middle Yellow shade)

Dror
Guest
Dror

Almost got it …
For some reason it colors only the outside and not the fill.
Any advice?

scale_fill_gradientn(aesthetics = c(“colour”, “fill”),
colours=c(‘red’,’yellow’,’green’),
limits=c(0.5,0.9),
oob = scales::squish)

Azis
Guest
Azis

Do the last code line of “# 3/ Custom bar width ” not finish yet?