Skip to Main Content

Data Visualization with R

Basic Data Visualization with R

BASIC DATA VISUALIZATION IN R 

Dataset description 

The mtcars dataset is a pre-loaded dataset in R that comes with the datasets package. It contains various car attributes, such as miles per gallon (mpg), number of cylinders (cyl), horsepower (hp), and so on. This dataset is often used for demonstration and teaching purposes.

Accessing the Dataset

You can access the dataset directly by calling its name:

data(mtcars)
Viewing the Dataset

To view the first few rows of the dataset, you can use the head() function:

head(mtcars)

Let's go through different types of charts you can create using the mtcars dataset in R. We'll use ggplot2 for these examples, which is a popular data visualization package in R. If you haven't installed it yet, you can do so with install.packages("ggplot2")

Bar Chart

Regular Simple Bar Chart
library(ggplot2) 
ggplot(mtcars, aes(x=factor(cyl))) + 
  geom_bar() + 
  xlab("Number of Cylinders") + 
  ylab("Frequency")
Customized Simple Bar Chart
ggplot(mtcars, aes(x=factor(cyl))) + 
  geom_bar(fill="blue", color="black") + 
  xlab("Number of Cylinders") + 
  ylab("Frequency") + 
  theme_minimal()

Histogram

Regular Histogram
ggplot(mtcars, aes(x=mpg)) + 
 geom_histogram(binwidth=5) + 
 xlab("Miles Per Gallon") + 
 ylab("Frequency")
Customized Histogram
ggplot(mtcars, aes(x=mpg)) + 
 geom_histogram(fill="purple", alpha=0.7, binwidth=5) + 
 xlab("Miles Per Gallon") + 
 ylab("Frequency") + 
 theme_bw()

Line Chart

Regular Line Chart
ggplot(mtcars, aes(x=wt, y=mpg)) + 
 geom_line() + 
 xlab("Weight") + 
 ylab("Miles Per Gallon")

Customized Line Chart
ggplot(mtcars, aes(x=wt, y=mpg)) + 
 geom_line(color="orange", size=1.5) + 
 xlab("Weight") + 
 ylab("Miles Per Gallon") + 
 theme_dark()

Scatter Plot

Regular Scatter Plot
ggplot(mtcars, aes(x=hp, y=mpg)) + 
 geom_point() + 
 xlab("Horsepower") + 
 ylab("Miles Per Gallon")
Customized Scatter Plot
ggplot(mtcars, aes(x=hp, y=mpg)) + 
 geom_point(color="red", size=4, shape=2) + 
 xlab("Horsepower") + 
 ylab("Miles Per Gallon") + 
 theme_classic()

Area Chart

Regular Area Chart
ggplot(mtcars, aes(x=wt, y=mpg)) + 
 geom_area(aes(fill=factor(cyl))) + 
 xlab("Weight") + 
 ylab("Miles Per Gallon")
Customized Area Chart
ggplot(mtcars, aes(x=wt, y=mpg)) + 
 geom_area(aes(fill=factor(cyl)), alpha=0.5) + 
 scale_fill_brewer(palette="Dark2") + 
 xlab("Weight") + 
 ylab("Miles Per Gallon") + 
 theme_minimal()

You can run each block of code in your R environment to generate the charts. This will allow you to see how customization can enhance the visual appeal and interpretability of your data visualizations.