ggplot2 Tutorial with Iris Dataset
Getting Started
Install and load ggplot2:
[Link]("ggplot2")
library(ggplot2)
Dataset Used
Using built-in iris dataset:
head(iris)
1. Basic Scatter Plot
ggplot(iris, aes(x = [Link], y = [Link])) +
geom_point()
2. Color by Category
ggplot(iris, aes(x = [Link], y = [Link], color = Species)) +
geom_point()
3. Boxplot
ggplot(iris, aes(x = Species, y = [Link])) +
geom_boxplot()
4. Histogram
ggplot(iris, aes(x = [Link])) +
geom_histogram(binwidth = 0.3, fill = 'skyblue', color = 'black')
5. Density Plot
ggplot2 Tutorial with Iris Dataset
ggplot(iris, aes(x = [Link], fill = Species)) +
geom_density(alpha = 0.6)
6. Line Plot (Summary Example)
iris_avg <- iris %>%
group_by(Species) %>%
summarize(mean_sepal = mean([Link]))
ggplot(iris_avg, aes(x = Species, y = mean_sepal)) +
geom_line(group = 1) +
geom_point()
7. Violin Plot
ggplot(iris, aes(x = Species, y = [Link], fill = Species)) +
geom_violin(trim = FALSE)
8. Bar Plot
ggplot(iris, aes(x = Species)) +
geom_bar(fill = 'coral') +
labs(title = 'Count of Each Species')
9. Themes and Labels
ggplot(iris, aes(x = [Link], y = [Link], color = Species)) +
geom_point(size = 3) +
labs(title = 'Sepal Dimensions by Species',
x = 'Sepal Length (cm)', y = 'Sepal Width (cm)') +
theme_minimal()
10. Faceting
ggplot2 Tutorial with Iris Dataset
ggplot(iris, aes(x = [Link], y = [Link])) +
geom_point() +
facet_wrap(~ Species)
11. Trend Lines
ggplot(iris, aes(x = [Link], y = [Link], color = Species)) +
geom_point() +
geom_smooth(method = 'lm', se = FALSE)
12. Save Plot
ggsave('iris_scatter.png', width = 6, height = 4)