Visualization with Base R
R has always included a package of graphics functions, so you do not need to install anything extra. These “Base Graphics” are:
- plot() as a universal tool,
- hist() for histograms,
- boxplot() for box plots,
- barplot() for bar charts.
These functions have several advantages—you do not need any extra packages, they are fast and directly available, and they are sufficient for initial exploratory steps. At the same time, however, they are somewhat less flexible than other packages we will get to know, and some customizations are not entirely user-friendly. Nevertheless, R base is sufficient for many everyday tasks!
Simple chart types
Histogram
Syntax: hist(x, main=…, xlab=…, col=…)
- main = title
- xlab, ylab = axis labels
- col = bar color
Result: An overview of the distribution. You can see where most of the data lie.
x <- c(2,3,3,4,6,7,9,9,10)
hist(x,
main="Histogramm of X",
xlab="Values",
col="skyblue")
Box plot
Syntax: boxplot(x, main=…, horizontal=TRUE/FALSE, col=…)
Shows the median (thick line inside the box), Q1/Q3 (box edges), whiskers, and, where applicable, outliers as points.
boxplot(x,
main="Boxplot of X",
col="orange",
horizontal=TRUE)
Bar chart (barplot)
Typically used for categorical data.
# Frequency calculation of a categorical variable
farbe <- c("red","red","blue","green","red","blue")
tab <- table(colours)
barplot(tab,
main="Colour Bar Chart",
col=c("red","blue","green"))
- table(colours) counts how often red, blue, and green occur.
- barplot() visualizes the results.
Scatter plot
For two numerical variables x and y:
x <- c(1,2,3,4,5)
y <- c(2,3,7,8,11)
plot(x, y,
main="Scatterplot X vs Y",
xlab="X-Axis",
ylab="Y-Axis",
pch=19,
col="darkgreen")
- pch=19: filled points
- col=”darkgreen”: color
Plot customizations
Base R plotting has a whole range of parameters for changing the appearance:
- pch: Point type (19 = filled circle, 1 = open circle, etc.)
- xlim, ylim: Ranges of the x- and y-axes (e.g., xlim=c(0,10))
- axes=FALSE: Hide the axes (you may then need to draw them manually)
- par(mfrow=c(r,c)): Multiple plots on one page
Example: Multiple plots side by side
par(mfrow=c(1,2)) # 1 row, 2 columns
hist(x, main="Hist X")
boxplot(x, main="Boxplot X")
Note: par(mfrow=…) remains in effect until you restart R or reset it with par(mfrow=c(1,1)).
Exporting graphics
With Base R, you can save your graphics in formats such as PNG, JPEG, PDF, and more.
Example:
png("mein_plot.png", width=600, height=400)
hist(x, main="Histogram of x")
dev.off()
- png(“filename.png”, …): Opens a PNG “drawing canvas”.
- All plot commands in between are drawn to this file.
- dev.off() closes the file.
Alternatively:
pdf("mein_plot.pdf")
boxplot(x)
dev.off()
Conclusion
You now know the basic ideas and most important commands for Base R Graphics:
- hist(), boxplot(), plot(), barplot()
- Customization options via parameters
- Export to various formats
