Plot Enhancement

Back

Loading concept...

🎨 Base R Visualization: Plot Enhancement

Imagine you’re an artist with a blank canvas. Base R plots are your canvas, and these enhancement tools are your paintbrushes, rulers, and frames!


🌟 The Big Picture

You’ve made a basic plot in R. Great! But it looks plain. Like a cake without frosting. Let’s add the frosting—legends, lines, text, grids, and more—to make your plots beautiful and informative.

Our Analogy: Think of your plot as a coloring book page. We’re about to add:

  • Labels (so people know what colors mean)
  • Extra drawings (lines and points)
  • Words (text annotations)
  • Ruler lines (grids)
  • Frame settings (margins and arrangements)
  • And finally, we’ll save our masterpiece!

📚 Legend Function

What is a Legend?

A legend is like a map key. When you color different things with different colors, the legend tells people what each color means.

Simple Example

# Draw two lines
plot(1:5, type="l", col="red")
lines(1:5 * 1.5, col="blue")

# Add a legend
legend("topleft",
       legend = c("Apples", "Oranges"),
       col = c("red", "blue"),
       lty = 1)

Key Parts of legend()

Argument What It Does Example
position Where to put it "topleft", "bottomright"
legend The labels c("Cat", "Dog")
col Colors to show c("red", "blue")
lty Line type 1 = solid, 2 = dashed
pch Point symbol 16 = filled circle

Where Can You Put It?

graph TD A["Legend Positions"] --> B["topleft"] A --> C["top"] A --> D["topright"] A --> E["left"] A --> F["center"] A --> G["right"] A --> H["bottomleft"] A --> I["bottom"] A --> J["bottomright"]

💡 Pro tip: Use legend("topleft", ...) to keep it out of the way of your data!


➕ Adding Lines and Points

Adding More Lines with lines()

Already drew a plot? Want to add another line on top? Use lines().

# First, make a plot
plot(1:10, 1:10, type="l", col="green")

# Add another line
lines(1:10, 10:1, col="purple")

Adding Points with points()

Want to mark specific spots? Use points().

# Make a plot
plot(1:5, 1:5)

# Add special points
points(c(2, 4), c(3, 5),
       col="red", pch=19, cex=2)

Point Symbols (pch)

pch Value Symbol
0 Square
1 Circle (empty)
16 Circle (filled)
17 Triangle (filled)
19 Big filled circle

Line Types (lty)

lty Value Style
1 Solid ───
2 Dashed ‐ ‐ ‐
3 Dotted ···
4 Dot-dash ·─·

✏️ Adding Text to Plots

The text() Function

Want to write words on your plot? Like adding labels to a drawing!

plot(1:5, 1:5)

# Add text at specific spot
text(3, 4, "Hello!", col="blue")

Positioning Text

Argument What It Does
x, y Where to put text
labels What to write
pos Side (1=below, 2=left, 3=above, 4=right)
cex Text size (1=normal, 2=double)

The mtext() Function

For text in the margins (edges of your plot):

plot(1:5, 1:5)

# Add margin text
mtext("Top Label", side=3)
mtext("Bottom Label", side=1)

Side numbers: 1=bottom, 2=left, 3=top, 4=right


📏 Grid Lines

Adding a Grid

Grids are like the lines on graph paper. They help you read values!

plot(1:10, 1:10)

# Add grid
grid()

Customizing Your Grid

plot(1:10, 1:10)

# Fancy grid
grid(nx = 5, ny = 5,    # 5 lines each way
     col = "lightgray",
     lty = 2)           # dashed

Using abline() for Lines

Draw straight lines anywhere!

plot(1:10, 1:10)

# Horizontal line at y=5
abline(h = 5, col = "red")

# Vertical line at x=3
abline(v = 3, col = "blue")

# Diagonal line
abline(a = 0, b = 1, col = "green")

⚙️ The par() Function

Your Plot Control Panel

par() is like the settings menu for ALL your plots. Change it once, and it affects everything after!

Common Settings

# See current settings
par()

# Change settings
par(bg = "lightyellow",   # background
    col = "darkblue",     # default color
    cex = 1.2)            # text size

Important Parameters

Parameter What It Controls
bg Background color
col Default color
cex Text/point size multiplier
lwd Line width
las Axis label rotation
mar Margins
mfrow Multiple plot layout

Saving and Restoring Settings

# Save current settings
old_par <- par()

# Make changes
par(bg = "pink")
plot(1:5)

# Restore original
par(old_par)

🔲 Multiple Plot Arrangement

mfrow and mfcol

Want to show multiple plots at once? Like a comic strip!

# 2 rows, 2 columns of plots
par(mfrow = c(2, 2))

plot(1:5, main = "Plot 1")
plot(1:5, main = "Plot 2")
plot(1:5, main = "Plot 3")
plot(1:5, main = "Plot 4")

# Reset to single plot
par(mfrow = c(1, 1))

The Difference

Function Fill Order
mfrow By rows (left to right, top to bottom)
mfcol By columns (top to bottom, left to right)
graph LR subgraph mfrow A["1"] --> B["2"] C["3"] --> D["4"] end

Using layout()

For unequal plot sizes:

# Create layout matrix
layout(matrix(c(1, 1, 2, 3),
              nrow = 2, byrow = TRUE))

plot(1:10, main = "Big plot")
plot(1:5, main = "Small 1")
plot(1:5, main = "Small 2")

📐 Plot Margins

Understanding mar

Margins are the empty space around your plot. Like the frame around a picture!

# mar = c(bottom, left, top, right)
par(mar = c(5, 4, 4, 2))

Default Values

graph TD subgraph Margins A["Top: 4 lines"] B["Right: 2 lines"] C["Bottom: 5 lines"] D["Left: 4 lines"] end

Making Room for Labels

# More space at bottom for long labels
par(mar = c(7, 4, 4, 2))
plot(1:5, xlab = "")
mtext("Long label here", side = 1,
      line = 5)

Outer Margins with oma

For space around multiple plots:

par(mfrow = c(2, 2),
    oma = c(2, 2, 3, 2))  # outer margins

plot(1:5); plot(1:5)
plot(1:5); plot(1:5)

mtext("Main Title", outer = TRUE,
      side = 3, cex = 1.5)

💾 Saving Plots to Files

Why Save Plots?

So you can use them in reports, presentations, or share with friends!

PNG Format (Pictures)

# Start saving
png("my_plot.png",
    width = 800, height = 600)

# Make your plot
plot(1:10, main = "My Plot")

# Stop saving
dev.off()

PDF Format (Documents)

pdf("my_plot.pdf",
    width = 8, height = 6)

plot(1:10, main = "My Plot")

dev.off()

Other Formats

Function Format Best For
png() PNG Web, screens
pdf() PDF Documents, printing
jpeg() JPEG Photos
svg() SVG Scalable graphics

Key Parameters

Parameter What It Does
width Image width (pixels or inches)
height Image height
res Resolution (for png/jpeg)
bg Background color

Complete Example

# Save a fancy plot
png("final_plot.png",
    width = 800,
    height = 600,
    res = 100)

par(mar = c(5, 4, 4, 2))
plot(1:10, 1:10,
     col = "blue",
     pch = 19,
     main = "My Data")
grid()
legend("topleft",
       legend = "Points",
       pch = 19,
       col = "blue")

dev.off()  # Don't forget this!

⚠️ Important: Always call dev.off() when you’re done! Otherwise, your file won’t save properly.


🎯 Quick Reference Flow

graph TD A["Create Basic Plot"] --> B["Add Data"] B --> C{Enhance?} C --> D["legend - add key"] C --> E["lines/points - add data"] C --> F["text/mtext - add labels"] C --> G["grid/abline - add guides"] D --> H["par - adjust settings"] E --> H F --> H G --> H H --> I["Save to file"]

🌈 You Did It!

You now know how to:

  • ✅ Add legends to explain your colors
  • ✅ Draw extra lines and points
  • ✅ Write text anywhere on your plot
  • ✅ Add helpful grid lines
  • ✅ Control all settings with par()
  • ✅ Arrange multiple plots together
  • ✅ Adjust margins for perfect spacing
  • ✅ Save your masterpiece to a file

Remember: Every great data visualization starts simple and gets enhanced one step at a time. You’ve got all the tools now—go make something beautiful! 🎨

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.