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



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:

TEXT 📖 Display only
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

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?

100%
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
💡 Tip: Use basic R (fast) for quick data analysis, and ggplot2 (beautiful) for report writing and research papers. This lesson covers basic R; the next lesson will cover ggplot2.



4. plot(): Versatile Plots (Primarily Scatter Plots)

(1) Basic Scatter Plot

R
# Plot a scatter plot of two columns of data
x <- 1:10
y <- x ^ 2
plot(x, y)

(2) Common Parameters

R
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
R
# 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()

R
# 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")

R
# 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()

R
# 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()

R
# 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))
⚠️ Note: Pie charts are not recommended—the human eye is not sensitive to angles, so bar charts are more accurate. The author of ggplot2 also recommends using geom_bar() instead of pie().

(5) Histogram hist()

R
# 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()

R
# 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

R
# 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

R
# 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

R
# 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
R
plot(1:25, pch = 0:25, cex = 2)


8. Comparison with ggplot2

(1) Two Ways to Draw the Same Figure

R
# 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

R
# ============================================
# 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))
▶ Try it Yourself

Expected output: 6 charts (line, bar, pie, histogram, box plot, and stacked bar) arranged in a 2x3 grid.


❓ FAQ

Q Which should I use—basic R or ggplot2?
A Use basic R for a quick look at your data (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.
Q Does the par() setting affect subsequent operations?
A Yes! 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().
Q How do I save an image to a file?
A Use png() / pdf() / jpeg(), etc.:
R
png("myplot.png", width = 800, height = 600)
plot(1:10)
dev.off()
Q What should I do if the text in the figure is garbled?
A Add par(family = "PingFang SC") (macOS) or family = "SimHei" (Windows). For Linux, use family = "WenQuanYi Zen Hei". For ggplot2, use theme(text = element_text(family = ...)).
Q How do I create a multi-plot layout?
Apar(mfrow = c(row, col)) Even distribution ② layout(matrix(...)) Flexible layout ③ Use facet_wrap() in ggplot2 to group by (more powerful).
Q Can I change the style of plots created with basic R?
A Yes, but it's tedious—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


📝 Exercises

  1. Basic Problem: Construct a vector sales <- c(100, 150, 200, 180, 220), use type = "p", "l", "b", and "h" to draw four figures (using par(mfrow = c(2, 2))), and verify the differences between the four figures.

  2. Basic Exercise: Use barplot() to create a sales comparison chart for 5 cities (with custom names), and include the 4 parameters col = rainbow(5), main, xlab, and ylab.

  3. Basic Exercise: Use hist() to plot a histogram of 1,000 random numbers generated by rnorm(100, 15), add the parameters breaks = 30 and col = "lightblue", and verify that the distribution approximates a normal distribution.

  4. Advanced Exercise: Simulate the grades for 4 classes of 10 students each (using list() or data.frame), then use boxplot() to plot a grade distribution chart for Class 4, adding colors and a title.

  5. 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, use png("report.png", 1200, 800) to save them as a single composite chart.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏