Types of Plots Using ggplot2 in R Programming Language
Introduction to ggplot2
The ggplot2 package in R is a powerful tool for data visualization. It follows the grammar of
graphics approach to create complex plots using simple building blocks.
Basic Syntax:
ggplot(data, aes(x, y)) + geom_XXX()
Install ggplot2
[Link]("ggplot2")
Summary Table
Plot Type geom Used Description
Scatter geom_point() Relationship between 2 variables
Line geom_line() Trends over time
Bar geom_bar() Count of categories
Histogra geom_histogram() Distribution of numeric variable
m
Boxplot geom_boxplot() Statistical summary
Violin geom_violin() Distribution shape and summary
Density geom_density() Smooth distribution curve
Area geom_area() Cumulative values
Facet facet_wrap() Subplots for each group
Heatmap geom_tile() Color-coded matrix
Pie Chart geom_col() + coord_polar() Pie visualization
1. Scatter Plot
Use: Explore relationship between two continuous variables.
library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point(color = "blue") +
labs(title = "MPG vs Weight")
2. Line Plot
Use: Show trend over time or ordered data.
ggplot(economics, aes(x = date, y = unemploy)) +
geom_line(color = "red") +
labs(title = "Unemployment Over Time")
3. Bar Chart
Use: Compare counts or values across categories.
ggplot(mpg, aes(x = class)) +
geom_bar(fill = "steelblue") +
labs(title = "Count of Vehicle Classes")
4. Histogram
Use: Show distribution of a single continuous variable.
ggplot(mpg, aes(x = hwy)) +
geom_histogram(bins = 20, fill = "darkgreen") +
labs(title = "Distribution of Highway MPG")
5. Boxplot
Use: Summarize distribution using quartiles and identify outliers.
ggplot(mpg, aes(x = class, y = hwy)) +
geom_boxplot(fill = "lightblue") +
labs(title = "Boxplot of Highway MPG by Class")
6. Violin Plot
Use: Combine boxplot and density plot.
ggplot(mpg, aes(x = class, y = hwy)) +
geom_violin(fill = "plum") +
labs(title = "Violin Plot of Highway MPG by Class")
7. Density Plot
Use: Show distribution and estimate probability density.
ggplot(mpg, aes(x = hwy)) +
geom_density(fill = "skyblue") +
labs(title = "Density Plot of Highway MPG")
8. Area Plot
Use: Show cumulative data trends over time.
ggplot(economics, aes(x = date, y = psavert)) +
geom_area(fill = "lightgreen") +
labs(title = "Personal Savings Rate Over Time")
9. Facet Plot
Use: Create multiple plots by grouping a variable.
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point() +
facet_wrap(~ class) +
labs(title = "Faceted Plot by Vehicle Class")
10. Heatmap
Use: Show data values in a matrix format.
data <- [Link](x = 1:5, y = 1:5)
data$z <- runif(25)
ggplot(data, aes(x, y, fill = z)) +
geom_tile() +
labs(title = "Heatmap Example")
11. Pie Chart
Use: Display parts of a whole.
data <- [Link](
category = c("A", "B", "C"),
count = c(10, 20, 30)
)
ggplot(data, aes(x = "", y = count, fill = category)) +
geom_col() +
coord_polar(theta = "y") +
labs(title = "Pie Chart")