Visualizing Data in R with Default Package:
Bar Plot and Pie Chart

Asst. Prof. Dr. Somsak Chanaim

International College of Digital Innovation, CMU

June 23, 2026

Example of Bar Plots

Bar Plot

A bar plot is a type of chart or graph that uses bars to represent data values.

It is essentially a visual display of information where individual bars or columns correspond to different categories or groups, and the length or height of each bar reflects the magnitude of the data it represents.

Bar plots are commonly used for visualizing categorical data and making comparisons between different groups.

The bar plot components:

Axes:

  • The horizontal axis typically represents categories or groups.

  • The vertical axis represents the values, frequencies, or percentages associated with each category.

Bars:

  • Each bar is a rectangular column that extends from the baseline (zero) to a height corresponding to the value it represents.

  • The width of the bars may vary, but they are usually uniform.

Spacing:

  • There is often some space between adjacent bars to visually separate them.

bar plots are useful for showing the distribution of data, identifying patterns, and making comparisons between different categories.

Bar Plot Using R Programming

In R, you can create a bar plot using the barplot() function. We will create a basic bar plot with random data:

Let’s break down the code:

vector:

  • values is a vector containing the corresponding values for each category.

  • categories is a vector containing the names of the categories.

argument:

  • height is the data you want to visualize. (numeric variable)

  • names.arg is used to specify the names of the categories. (character/factor variable)

  • col sets the color of the bars (you can choose any color).

  • main sets the title of the plot.

  • ylab and xlab set the labels for the y-axis and x-axis, respectively.

The table() Function

The table() function in R is used to create a contingency table, which shows the frequency distribution of a variable or the cross-tabulation of multiple variables.

It counts the number of occurrences of each unique value in a vector, factor, or set of factors.

Create the Bar Plot from table() Function

Example with Pipe Operator

Add More Color to each Bar

Rotate Graph

Rotate graph by set horiz =TRUE

Ordering the variable ‘money’ from the minimum to the maximum value.

color: “#ffff00”

color: “#0000ff”

Transpose table

Listing 1

Stacked bar plot

Use t() to create another stacked bar plot

Using t() flips the table, so now each gender groups the bars, making it easier to compare faculties within gender.

Grouped Bar Plot

The argument beside = TRUE is used to create grouped bar plots, where bars corresponding to different categories are placed side by side, rather than stacked on top of each other.

color: “#ff0000”

color: “#00ff00”

color: “#0000ff”

Exercise

Exercise 1: Fundamental Bar Plot Architecture

Complete the executable script to compile categorical frequencies and render a baseline bar plot with descriptive axis labels.

Target output

Complete the code

data(mtcars)
gear_freq <- (mtcars$gear)
(gear_freq,
main = "Frequency of Gear Types in mtcars",
= "Number of Gears",
= "Frequency",
col = "lightblue",
border = "black")

Exercise 2: Horizontal Bar Plot Configuration

Complete the script to compute categorical cylinder frequencies and render a horizontal bar plot with customized aesthetic parameters.

Target output

Complete the code

cyl_freq <- table(mtcars$cyl)
barplot(cyl_freq,
= TRUE,
main = "Frequency of Cylinder Types in mtcars",
xlab = "Frequency",
ylab = "Number of Cylinders",
= "lightgreen",
border = "black")

Exercise 3: Grouped Bar Plot Architecture

Complete the script to construct a multi-dimensional contingency table and render a grouped bar plot utilizing a segmented legend layout.

Target output

Complete the code

cyl_gear_table <- table(mtcars$cyl, mtcars$gear)
barplot(cyl_gear_table,
= TRUE,
main = "Cylinder Types by Gear Types",
xlab = "Number of Gears",
ylab = "Frequency",
col = c("red", "green", "blue"),
= rownames(cyl_gear_table),
args.legend = list(title = "Cylinders", x = "topright"))

Exercise 4: Stacked Bar Plot Architecture

Complete the script to compute a contingency matrix and render a stacked bar plot deploying a customized segmented color palette.

Target output

Complete the code

cyl_gear_table <- table(mtcars$cyl, mtcars$gear)
(cyl_gear_table,
main = "Stacked Bar Plot of Cylinder Types by Gear Types",
xlab = "Number of Gears",
ylab = "Frequency",
= c("red", "green", "blue"),
legend.text = rownames(cyl_gear_table),
args.legend = list(title = "Cylinders", x = "topright"))

Exercise 5: Advanced Aesthetic and Label Customization

Complete the script to aggregate species frequencies and render a highly customized bar plot with explicit mapping names and bar widths.

Target output

Complete the code

species_freq <- table(iris$Species)
barplot(species_freq,
main = "Frequency of Species in Iris Dataset",
xlab = "Species",
ylab = "Frequency",
col = c("purple", "orange", "cyan"),
= c("Setosa", "Versicolor", "Virginica"),
= 0.7,
border = "black")

Example of Pie Chart

Pie Chart

A pie chart is a circular statistical graphic that is divided into slices to illustrate numerical proportions. In R, you can create a pie chart using the pie() function.

See Listing 1 for details.

pie() Function:

  • The pie() function creates a pie chart.

  • The first argument x is the data you want to visualize, which in this case is the frequency of different cylinder types.

  • The main argument specifies the title of the chart.

  • The col argument is used to set custom colors for the slices of the pie chart.

  • The labels argument customizes the labels that appear on the slices of the pie chart.

Why pie chart is not useful?

The pie chart is one of the most popular charts — but also one of the most criticized in data visualization.

❌ Why pie charts are often not recommended:

  1. 🎯 Humans are bad at comparing angles

    • It’s hard for people to accurately compare the size of pie slices

    • especially when values are close.

    • Bar charts allow for easier and more accurate comparison using length, not angle.

Example: Can you easily tell the difference between 23% and 27% in a pie chart? Not really.

  1. 🍩 Too many slices = confusion

    • Pie charts get messy with more than 4–5 categories.

    • Colors become harder to distinguish.

    • Labels may overlap or require a legend, which makes interpretation slower.

  2. 📉 No clear axis = no easy comparison

    • There’s no y-axis or consistent baseline.

    • We lose the advantage of alignment (as in bar plots) which helps the eye compare quantities.

  3. 📊 Bar chart does everything better

    • Bar charts:

      • Are easier to read

      • Handle small differences better

      • Are simpler to label

      • Are more scalable to many categories

✅ When pie charts might still be acceptable:

Use Case Okay?
Only 2–3 clear categories ✅ Yes
Audience is general/public ✅ Maybe
Style or storytelling focus ✅ Yes (e.g. in infographics)
Detailed analysis or comparison ❌ No

🔁 Summary: Pie vs Bar

Feature Pie Chart Bar Chart
Easy to compare ❌ Hard ✅ Easy
Best for small N ✅ Yes (2–3 items) ✅ Yes (scalable)
Labels/readability ❌ Poor ✅ Better
Style/visual appeal ✅ Sometimes ⚖️ Depends on use

🧠 Expert Opinions:

  • Edward Tufte (data viz pioneer): “The only thing worse than a pie chart is several of them.”

  • Stephen Few: Recommends bar or dot plots for almost every case where pie charts are used.