R Tutorial



R GRAPHICS


Graphics in R

R provides powerful tools for data visualization. The base R system and additional libraries like ggplot2 allow us to create various types of plots to explore and present data effectively.

Basic Plotting with Base R

Let’s start with simple visualizations using base R.

# Sample data
x <- c(1, 2, 3, 4, 5)
y <- c(10, 20, 15, 25, 30)

# Create a basic line plot
plot(x, y, type = "o", col = "blue", main = "Line Plot", xlab = "X Axis", ylab = "Y Axis")
  

Types of Plots in Base R

  • plot() – Scatter or line plots
  • barplot() – Bar charts
  • hist() – Histograms
  • boxplot() – Boxplots for statistical summary
  • pie() – Pie charts

Bar Plot Example

values <- c(20, 35, 30, 40)
names <- c("A", "B", "C", "D")

barplot(values, names.arg = names, col = "skyblue", main = "Bar Plot")
  

Histogram Example

data <- c(5, 10, 20, 20, 15, 10, 25, 30)
hist(data, col = "orange", main = "Histogram", xlab = "Value")
  

Boxplot Example

scores <- c(55, 70, 65, 80, 90, 85, 60)
boxplot(scores, main = "Boxplot of Scores", col = "lightgreen")
  

Pie Chart Example

slices <- c(30, 25, 20, 25)
labels <- c("Math", "Science", "History", "English")

pie(slices, labels = labels, col = rainbow(4), main = "Subjects Pie Chart")
  

Advanced Graphics: ggplot2

ggplot2 is a powerful package for creating advanced and customized visualizations in R.

# Install and load ggplot2 (only once)
# install.packages("ggplot2")
library(ggplot2)

# Sample dataframe
df <- data.frame(
  x = c(1, 2, 3, 4, 5),
  y = c(10, 20, 15, 25, 30)
)

# Create a scatter plot
ggplot(df, aes(x, y)) +
  geom_point(color = "blue") +
  ggtitle("Scatter Plot with ggplot2")
  

Tips for Effective Graphs

  • Use clear labels (xlab, ylab, main)
  • Use color and legends meaningfully
  • Choose the right chart type for your data
  • Keep charts simple and readable

Practice Exercises

  • Create a bar chart of your monthly expenses.
  • Plot a histogram of random numbers using rnorm().
  • Draw a pie chart showing time spent on daily activities.
  • Use ggplot2 to create a line chart of sales data.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review