R: R Base Plotting
Last updated: 2026-08-26
This lesson kicks off the "Graphics" section of the R tutorial—Data Visualization. R has two plotting systems: base R (
plot/line/bar) and ggplot2 (ggplot + geom_). In this lesson, we’ll start by learning base R plotting—it’s simple and fast, making it ideal for quickly checking data.
After completing this lesson, you'll be able to create six basic types of charts in R: scatter plots, line charts, bar charts, pie charts, histograms, and box plots.
1. What You'll Learn
- R Basic Graphics System (graphics package)
- 6 Core Charts: plot/line/bar/pie/hist/boxplot
- par() graphic parameters (color, font, layout)
- layout() Multi-image Layout
- Differences from ggplot2 (When to Use Which)
- Practical Guide: Sales Data Reports with Multiple Charts
2. A Story About Sales Visualization
(1) Pain Point: The table isn't intuitive enough
Bob presented the fourth-quarter sales figures to the manager:
Region Q1 Q2 Q3 Q4
Beijing 1000 1200 1100 1500
Shanghai 1500 1800 1700 2000
Guangzhou 800 900 1000 1200
The manager glanced at it and said, "I don't care about the numbers—just give me the chart."
(2) Solution using R
# 1. A Line Chart in One Line of Code(4 Quarterly City Trends)
plot(sales, type = "b", col = rainbow(4), main = "Quarterly Sales Trends")
# 2. Creating a bar chart in one line(4 Total City Sales)
barplot(rowSums(sales[, -1]), main = "Total Sales Comparison", col = "skyblue")
# 3. A Line Chart(Percentage)
pie(rowSums(sales[, -1]), labels = rownames(sales))
3 lines of code → 3 plots. That’s how fast basic R plotting is.
3. R's Two Plotting Systems
(1) Comparison
| Feature | Basic R (graphics) | ggplot2 |
|---|---|---|
| Speed | Extremely fast (10 lines) | Slower (tens of lines) |
| Ease of Learning | ✅ Simple | ❌ Steep learning curve |
| Default, Attractive | ❌ Basic | ✅ Publication-Quality |
| Flexibility | ⚠️ Limited | ✅ Highly flexible |
| Suitable Scenarios | Quick Data Review | Publications/Reports |
| Basic Syntax | "Drawing on the Canvas" | Grammar of Graphics |
(2) When to use which one?
graph TB
A[Imagination Drawing] --> B{Scene}
B -->|Quick Data Overview| C[Basics R plot]
B -->|Published/Report| D[ggplot2]
B -->|Teaching Demonstration| E[Either one is fine]
style A fill:#fff3cd
style C fill:#d4edda
style D fill:#cce5ff
4. plot(): Versatile Plots (Primarily Scatter Plots)
(1) Basic Scatter Plot
# Plot a scatter plot of two columns of data
x <- 1:10
y <- x ^ 2
plot(x, y)
(2) Common Parameters
plot(x, y,
type = "p", # Graph Type
main = "Title",
xlab = "X Axis",
ylab = "Y Axis",
col = "blue", # Color
pch = 19, # Point-shaped(0-25)
cex = 1.5, # Font Size
xlim = c(0, 12), # X Shaft Range
ylim = c(0, 110)) # Y Shaft Range
(3) 6 Types
| type | Meaning | Purpose |
|---|---|---|
"p" |
Points (default) | Scatter plot |
"l" |
Line | Line Chart |
"b" |
Points + Lines | Trend Chart |
"o" |
Point Through Line | Time Series |
"h" |
Vertical Line | Bar Chart (Line Version) |
"s" |
Stairs | Staircase Diagram |
# For the same set of data, 6 A Painting Technique
x <- 1:5
y <- c(2, 4, 3, 5, 4)
par(mfrow = c(2, 3)) # 2 row 3 Column Layout
for (t in c("p", "l", "b", "o", "h", "s")) {
plot(x, y, type = t, main = paste("type =", t))
}
5. 6 Core Charts
(1) Scatter Plot plot()
# 4 City Scatter Plot
x <- c(1, 2, 3, 4)
y <- c(1000, 1500, 800, 1200)
plot(x, y,
main = "City Sales Scatter Plot",
xlab = "City Code",
ylab = "Sales",
col = "blue",
pch = 19)
(2) Line chart plot(type = "l")
# Quarterly Trend Chart
quarters <- c("Q1", "Q2", "Q3", "Q4")
sales <- c(1000, 1200, 1100, 1500)
plot(quarters, sales,
type = "b", # Point + Line
main = "Q1-Q4 Sales Trends",
xlab = "Quarter",
ylab = "Sales",
col = "darkblue",
lwd = 2, # Line width
pch = 19)
(3) Bar Chart barplot()
# 4 City Sales Bar Chart
sales_data <- c(Beijing = 4800, Shanghai = 7000, Guangzhou = 3900, Shenzhen = 4500)
barplot(sales_data,
main = "Total Sales by City",
xlab = "City",
ylab = "Sales",
col = c("red", "blue", "green", "orange"),
border = "white",
horiz = FALSE) # TRUE Sideways
(4) Pie Chart pie()
# Sales Share Pie Chart
sales_data <- c(Beijing = 4800, Shanghai = 7000, Guangzhou = 3900, Shenzhen = 4500)
pie(sales_data,
main = "Share of Sales",
col = rainbow(4),
labels = paste0(names(sales_data), "\n", sales_data))
geom_bar() instead of pie().
(5) Histogram hist()
# 1000 The Distribution of a Random Number
data <- rnorm(1000, mean = 100, sd = 15)
hist(data,
main = "Normal Distribution",
xlab = "Value",
ylab = "Frequency",
col = "lightblue",
border = "white",
breaks = 30) # min 30 a range
(6) Box Plot boxplot()
# 4 Class Exam Score Distribution
scores <- list(
1Cls = c(85, 90, 78, 92, 88, 76, 95, 80),
2Cls = c(72, 80, 85, 78, 90, 88, 82, 75),
3Cls = c(95, 88, 92, 90, 85, 78, 80, 88),
4Cls = c(60, 65, 70, 75, 80, 85, 90, 95)
)
boxplot(scores,
main = "4 Class Grade Distribution",
xlab = "Class",
ylab = "Fractions",
col = c("red", "blue", "green", "orange"))
6. par() Graph Parameters
(1) par Quick Reference Table
| Parameter | Function | Example |
|---|---|---|
mfrow |
Multi-image layout (rows × columns) | par(mfrow = c(2, 2)) |
mar |
Margin (4 digits) | par(mar = c(5, 4, 4, 2)) |
bg |
Background color | par(bg = "lightyellow") |
col |
Default Color | par(col = "blue") |
cex |
Default text size | par(cex = 1.2) |
lty |
Solid line | par(lty = 2) Dashed line |
pch |
Dot Shape | par(pch = 19) |
(2) Multi-image Layout
# 2x2 Layout
par(mfrow = c(2, 2))
plot(1:10, main = "Plot 1")
plot(1:10, type = "l", main = "Plot 2")
barplot(1:5, main = "Plot 3")
pie(1:4, main = "Plot 4")
# Restore Default Layout
par(mfrow = c(1, 1))
(3) layout() Flexible Layout
# 1 L + 4 S Layout
layout(matrix(c(1, 1, 2, 3,
1, 1, 4, 5), nrow = 2, byrow = TRUE))
plot(1:10, main = "Large Image") # 1
plot(1:5, main = "Small image 1") # 2
plot(1:5, main = "Small image 2") # 3
plot(1:5, main = "Small image 3") # 4
plot(1:5, main = "Small image 4") # 5
layout(1) # Restore
7. Color and Point Shape
(1) Color
# 1. Name
plot(1:5, col = "red")
plot(1:5, col = "blue")
plot(1:5, col = "darkgreen")
# 2. Hexadecimal
plot(1:5, col = "#FF0000")
plot(1:5, col = "#3366CC")
# 3. rainbow() Color Palette
barplot(1:7, col = rainbow(7))
barplot(1:7, col = heat.colors(7))
barplot(1:7, col = topo.colors(7))
barplot(1:7, col = terrain.colors(7))
(2) Point shape pch
| pch | Shape | Purpose |
|---|---|---|
| 0–6 | Hollow | Various shapes |
| 19–25 | Solid | Recommended (Clear) |
| 19 | Dots | Most Common |
| 17 | Triangle | Emphasis |
| 15 | Block | Binary |
plot(1:25, pch = 0:25, cex = 2)
8. Comparison with ggplot2
(1) Two Ways to Draw the Same Figure
# Data
df <- data.frame(x = 1:5, y = c(2, 4, 3, 5, 4))
# Basics R(5 row)
plot(df$x, df$y, type = "b", main = "Trends", xlab = "X", ylab = "Y",
col = "blue", pch = 19, lwd = 2)
# ggplot2(6 row,**By default, it looks better**)
library(ggplot2)
ggplot(df, aes(x = x, y = y)) +
geom_line(color = "blue") +
geom_point(color = "blue", size = 3) +
labs(title = "Trends", x = "X", y = "Y") +
theme_minimal()
(2) When to choose which one?
| Scenario | Recommendation |
|---|---|
| Quick Data Overview | Basic R (Plotting with One Line) |
| Publications/Papers | ggplot2 (Publication-Quality Visuals) |
| Tutorial | Basic R (Simple and Easy to Understand) |
| Standardized Report | ggplot2 (Unified Theme) |
| Parameter Tuning | ggplot2 (Fine-Tuning) |
9. Complete Example: Multi-Chart Report on Sales Data
Below is an example of a complete workflow that ties together all the diagrams from this lesson.
▶ Example: Visualization of Quarterly Sales in 4 Cities
# ============================================
# 4 Visualization of Quarterly City Sales
# Features:6 Comprehensive Display of Basic Charts
# ============================================
# 1. Prepare data
sales <- matrix(c(
1000, 1200, 1100, 1500, # Beijing
1500, 1800, 1700, 2000, # Shanghai
800, 900, 1000, 1200, # Guangzhou
1200, 1400, 1300, 1600 # Shenzhen
), nrow = 4, byrow = TRUE)
rownames(sales) <- c("Beijing", "Shanghai", "Guangzhou", "Shenzhen")
colnames(sales) <- c("Q1", "Q2", "Q3", "Q4")
print(sales)
# 2. Settings 2x3 Layout
par(mfrow = c(2, 3), mar = c(4, 4, 3, 1))
# 3. Plot 1:Line Chart(4 City)
plot(1:4, sales[1, ], type = "b", col = "red", ylim = c(0, 2500),
main = "Quarterly Sales Trends", xlab = "Quarter", ylab = "Sales",
pch = 19, lwd = 2, xaxt = "n")
axis(1, at = 1:4, labels = colnames(sales))
for (i in 2:4) {
lines(1:4, sales[i, ], type = "b", col = i, pch = 19, lwd = 2)
}
legend("topleft", legend = rownames(sales),
col = 1:4, pch = 19, lwd = 2, cex = 0.7)
# 4. Plot 2:Bar Chart(Total Sales)
barplot(rowSums(sales),
main = "Total Sales by City",
xlab = "City", ylab = "Total Sales",
col = c("red", "blue", "green", "orange"),
border = "white")
# 5. Plot 3:Pie Chart(Percentage)
pie(rowSums(sales),
main = "Share of Sales",
col = rainbow(4),
labels = paste0(rownames(sales), "\n", rowSums(sales)))
# 6. Plot 4:Histogram(Sales Distribution)
hist(sales, main = "Sales Distribution", xlab = "Sales",
col = "lightblue", border = "white", breaks = 10)
# 7. Plot 5:Box-and-Whisker Plot(By City)
boxplot(sales, main = "Quarterly Sales Breakdown by City",
xlab = "City", ylab = "Sales",
col = c("red", "blue", "green", "orange"))
# 8. Plot 6:Stacked Bar Chart
barplot(sales, beside = FALSE, # beside=FALSE → Stacked
main = "Quarterly Sales Stacked Chart",
xlab = "City", ylab = "Sales",
col = c("red", "blue", "green", "orange"),
legend.text = colnames(sales))
# 9. Restore Layout
par(mfrow = c(1, 1))
Expected output: 6 charts (line, bar, pie, histogram, box plot, and stacked bar) arranged in a 2x3 grid.
❓ FAQ
plot() barplot()—plotting with a single line of code), and use ggplot2 for reports and papers (it produces publication-quality visuals by default). Beginners should start with basic R and then move on to ggplot2.par() is a global setting; you must reset it after use (e.g., par(mfrow = c(1, 1))). In production code, it is recommended to use par() to reset it before dev.off().png() / pdf() / jpeg(), etc.:png("myplot.png", width = 800, height = 600)
plot(1:10)
dev.off()
par(family = "PingFang SC") (macOS) or family = "SimHei" (Windows). For Linux, use family = "WenQuanYi Zen Hei". For ggplot2, use theme(text = element_text(family = ...)).par(mfrow = c(row, col)) Even distribution ② layout(matrix(...)) Flexible layout ③ Use facet_wrap() in ggplot2 to group by (more powerful).col lwd pch cex—you have to adjust dozens of parameters one by one. ggplot2 uses theme() to apply a unified style, which is more efficient.📖 Summary
- R has two plotting systems: the standard R (graphics) and ggplot2
- Basic R: 6 Core Plots: plot (scatter plot) / plot type="l" (line plot) / barplot (bar chart) / pie (pie chart) / hist (histogram) / boxplot (box-and-whisker plot)
par()Set global parameters:mfrowMultiple images /marMargins /bgBackground /colColors /pchPoint styleslayout()Flexible Layout (1 Large + 4 Small)- Color using
"red"/"#FF0000"/rainbow(n) - Save the image using
png()+dev.off()orggsave() - Basic R is good for quickly exploring data, while ggplot2 is good for publishing—learn both and choose based on your needs
📝 Exercises
-
Basic Problem: Construct a vector
sales <- c(100, 150, 200, 180, 220), usetype = "p","l","b", and"h"to draw four figures (usingpar(mfrow = c(2, 2))), and verify the differences between the four figures. -
Basic Exercise: Use
barplot()to create a sales comparison chart for 5 cities (with custom names), and include the 4 parameterscol = rainbow(5),main,xlab, andylab. -
Basic Exercise: Use
hist()to plot a histogram of 1,000 random numbers generated byrnorm(100, 15), add the parametersbreaks = 30andcol = "lightblue", and verify that the distribution approximates a normal distribution. -
Advanced Exercise: Simulate the grades for 4 classes of 10 students each (using
list()ordata.frame), then useboxplot()to plot a grade distribution chart for Class 4, adding colors and a title. -
Challenge: Complete the workflow—simulate a sales matrix for 4 products across 4 quarters, and use
par(mfrow = c(2, 3))to create 6 charts: ① line chart showing trends, ② bar chart for comparison, ③ pie chart showing percentages, ④ histogram showing distribution, ⑤ box-and-whisker plot, ⑥ stacked bar chart. Finally, usepng("report.png", 1200, 800)to save them as a single composite chart.