The barplot()
function allows to build a
barplot in base R. Learn how to customize
the chart: color, bar width, orientation and more.
barplot()
function
This is the most basic barplot you can build with R and the barplot() funtion. It was described in graph #208.
This post describes how to custom this basic barplot.
# create dummy data
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5)
)
# The most basic barplot you can do:
barplot(height=data$value, names=data$name)
Here are 2 examples showing how to custom the barplot color:
col
, asking one color onlyRColorBrewer
border
argument# create dummy data
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5)
)
# Uniform color
barplot(height=data$value, names=data$name, col=rgb(0.2,0.4,0.6,0.6) )
# Specific color for each bar? Use a well known palette
library(RColorBrewer)
coul <- brewer.pal(5, "Set2")
barplot(height=data$value, names=data$name, col=coul )
# Change border color
barplot(height=data$value, names=data$name, border="#69b3a2", col="white" )
Usual customizations with xlab
, ylab
,
main
and ylim
.
# create dummy data
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5)
)
# Uniform color
barplot(height=data$value, names=data$name,
col=rgb(0.8,0.1,0.1,0.6),
xlab="categories",
ylab="values",
main="My title",
ylim=c(0,40)
)
Usual customizations with xlab
, ylab
,
main
and ylim
.
# create dummy data
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5)
)
# Uniform color
barplot(height=data$value, names=data$name,
col="#69b3a2",
horiz=T, las=1
)
It is possible to control the space between bars and the width of
the bars using space
and width
.
Can be usefull to represent the number of value behind each bar.
# create dummy data
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5)
)
# Control space:
barplot(height=data$value, names=data$name, col=rgb(0.2,0.4,0.6,0.6), space=c(0.1,0.2,3,1.5,0.3) )
# Control width:
barplot(height=data$value, names=data$name, col=rgb(0.2,0.4,0.6,0.6), width=c(0.1,0.2,3,1.5,0.3) )
Change bar texture with the density
and
angle
arguments.
👋 After crafting hundreds of R charts over 12 years, I've distilled my top 10 tips and tricks. Receive them via email! One insight per day for the next 10 days! 🔥