1.
Install and Load ggplot2
install.packages("ggplot2") # Install ggplot2 if not already installed
library(ggplot2) # Load the library
Basic ggplot2 Syntax
The ggplot() function initializes a plot, and you add layers using +:
ggplot(data, aes(x = variable1, y = variable2)) + geom_layer()
2. Scatter Plot
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
ggtitle("Scatter Plot of Weight vs MPG") +
xlab("Car Weight") + ylab("Miles Per Gallon") +
theme_minimal()
🔹 geom_point() creates a scatter plot.
3. Line Graph
ggplot(economics, aes(x = date, y = unemploy)) +
geom_line(color = "blue") +
ggtitle("Unemployment Over Time") +
xlab("Year") + ylab("Unemployment") +
theme_light()
🔹 geom_line() creates a line plot.
4. Bar Chart
ggplot(mpg, aes(x = class)) +
geom_bar(fill = "skyblue", color = "black") +
ggtitle("Count of Cars by Class") +
xlab("Car Class") + ylab("Count") +
theme_bw()
🔹 geom_bar() creates a bar chart.
5. Histogram
ggplot(mtcars, aes(x = mpg)) +
geom_histogram(binwidth = 5, fill = "orange", color = "black") +
ggtitle("Distribution of MPG") +
xlab("Miles Per Gallon") + ylab("Count") +
theme_classic()
🔹 geom_histogram() creates a histogram.
6. Boxplot
ggplot(mpg, aes(x = class, y = hwy)) +
geom_boxplot(fill = "pink") +
ggtitle("Highway MPG by Car Class") +
xlab("Car Class") + ylab("Highway MPG") +
theme_minimal()
🔹 geom_boxplot() creates a boxplot.
7. Faceted Plot
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point() +
facet_wrap(~class) +
ggtitle("Engine Displacement vs Highway MPG by Car Class")