0% found this document useful (0 votes)
0 views

data visualization ggplot

This document provides a guide on how to use the ggplot2 library in R for data visualization. It covers the installation of ggplot2, basic syntax, and examples of different plot types including scatter plots, line graphs, bar charts, histograms, boxplots, and faceted plots. Each example includes code snippets and descriptions of the functions used to create the visualizations.

Uploaded by

Hasham Younis
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

data visualization ggplot

This document provides a guide on how to use the ggplot2 library in R for data visualization. It covers the installation of ggplot2, basic syntax, and examples of different plot types including scatter plots, line graphs, bar charts, histograms, boxplots, and faceted plots. Each example includes code snippets and descriptions of the functions used to create the visualizations.

Uploaded by

Hasham Younis
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

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")

You might also like