Creating Data Visualizations using ggplot
Creating Data Visualizations using ggplot
html
We will create different data visualizations using the ggplot package using the inbuilt dataset in R called mtcars
1. Click on the + symbol on the top left and choose R Script from the menu to open a new R edit window in RStudio:
2. Read and view the first 5 rows of the Data using the following:
library(datasets)
# Load Data
data(mtcars)
# View first 5 rows
head(mtcars, 5)
3. Type this ?mtcars to get information about the variables. This will print the information at the bottom right panel, on the Help tab
4. Copy and paste the following code to load the ggplot package and create a scatterplot of disp and mpg.
# Add a title
ggplot(aes(x=disp,y=mpg,),data=mtcars)+geom_point()+ggtitle("displacement vs miles per gallon")
6. Use the following code to change the name of the x-axis and y-axis
https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DS0105EN-SkillsNetwork/labs/Module2/plotting_with_R.md.html 1/2
5/5/23, 3:43 PM https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DS0105EN-SkillsNetwork/labs/Module2/plotting_with_R.md.html
7. Use the following to create a boxplot of the the distribution of mpg for the individual Engine types vs Engine (0 = V-shaped, 1 =
straight)
#make vs a factor
mtcars$vs <- as.factor(mtcars$vs)
# create boxplot of the distribution for v-shaped and straight Engine
ggplot(aes(x=vs, y=mpg), data = mtcars) + geom_boxplot()
ggplot(aes(x=wt),data=mtcars) + geom_histogram(binwidth=0.5)
Author(s)
Aije Egwaikhide
Change log
Date Version Changed by Change Description
https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DS0105EN-SkillsNetwork/labs/Module2/plotting_with_R.md.html 2/2