R Chart Types: Syntax & Examples
R Chart Types: Syntax & Examples
Introduction
R offers rich capabilities for data visualization using both base R functions and powerful packages
like ggplot2. Below are the main chart types, their purposes, and their code examples.
1. Bar Chart
text
library(ggplot2)
sales_data <- [Link](product = c("A", "B", "C", "D"), sales = c(120, 150,
180, 90))
ggplot(sales_data, aes(x = product, y = sales)) +
geom_bar(stat = "identity", fill = "steelblue") +
labs(title = "Product Sales", x = "Product", y = "Sales Amount")
2. Histogram
text
ggplot(mtcars, aes(x = mpg)) +
geom_histogram(bins = 20, fill = "coral", color = "black") +
labs(title = "Distribution of Miles Per Gallon", x = "MPG", y = "Frequency")
3. Scatter Plot
text
# Base R
plot(mtcars$wt, mtcars$mpg, main = "Weight vs MPG", xlab = "Weight", ylab =
"Miles Per Gallon", pch = 19, col = "blue")
# ggplot2
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point(color = "darkgreen", size = 3) +
labs(title = "Weight vs MPG")
4. Line Chart
text
time_data <- [Link](year = 2015:2023, revenue = c(100, 120, 145, 160, 190,
210, 240, 280, 310))
ggplot(time_data, aes(x = year, y = revenue)) +
geom_line(color = "red", linewidth = 1.5) +
geom_point(size = 3) +
labs(title = "Revenue Growth Over Years", x = "Year", y = "Revenue (in
millions)")
5. Box Plot
text
ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +
geom_boxplot(fill = "lightblue", color = "darkblue") +
labs(title = "MPG Distribution by Cylinder Count", x = "Number of Cylinders",
y = "Miles Per Gallon")
text
area_data <- [Link](year = rep(2018:2023, 3), product = rep(c("Product A",
"Product B", "Product C"), each = 6), sales =
c(20,25,30,35,40,45,30,35,40,45,50,55,15,20,25,30,35,40))
ggplot(area_data, aes(x = year, y = sales, fill = product)) +
geom_area(alpha = 0.7) +
labs(title = "Stacked Area Chart of Product Sales", x = "Year", y = "Sales")
7. Pie Chart
text
market_share <- c(30, 25, 20, 15, 10)
companies <- c("Company A", "Company B", "Company C", "Company D", "Company E")
pie(market_share, labels = companies, main = "Market Share by Company", col =
rainbow(length(market_share)))
8. Correlogram
text
library(corrplot)
cor_matrix <- cor(mtcars[, c("mpg", "disp", "hp", "wt")])
corrplot(cor_matrix, method = "color", type = "upper", [Link] = "black",
[Link] = "black", [Link] = 45, title = "Correlation Matrix of Car Variables")
text
stacked_data <- [Link](region =
rep(c("North","South","East","West"),each=3), product=rep(c("Product
X","Product Y","Product Z"),4), sales=c(40,50,60,35,45,55,50,60,70,45,55,65))
ggplot(stacked_data, aes(x = region, y = sales, fill = product)) +
geom_bar(stat = "identity") +
labs(title = "Regional Sales by Product", x = "Region", y = "Sales Amount")
Conclusion
Choose a chart type based on your data and analytical goals. R’s ggplot2 and base plotting
functions enable publication-quality visualizations for a variety of analytical tasks.