R: Data Visualization – Creating Pie Chart, Bar Chart & Line Graph

This article shows how to create Pie chart, Bar chart & Line graph using R Programming Language.

Set Working Directory

Set a directory where you want to save the image of pie chart, bar chart & line graph.


> print (getwd()) # get current working directory
[1] "/home/mukesh"

> setwd('/home/mukesh/Documents/training') # set working directory 

> print (getwd())
[1] "/home/mukesh/Documents/training"

Creating Pie Chart

We will create a pie chart with 3 labels: English, Math and Science. We add some values to the labels.

A new file named subject_pass.png will be created in your working directory. It contains the pie chart.


> subjects <- c ('English', 'Math', 'Science') # labels
> passedStudents <- c (33, 25, 21) # values
> png(file = 'subject_pass.png') # image file name
> pie(passedStudents, subjects, main = 'Passed Students') # create pie chart
> dev.off() # save file

pie chart

Creating the same chart as above but with rainbow color (brighter colors)


> subjects <- c ('English', 'Math', 'Science') # labels
> passedStudents <- c (33, 25, 21) # values
> passedStudentsPercent <- round(100 * passedStudents / sum(passedStudents), 1)
> jpeg(file = 'subject_pass.jpg')
> pie(x = passedStudents, labels = passedStudentsPercent, main = 'Passed Students', col = rainbow(length(passedStudents)))
> legend('topright', subjects, fill = rainbow(length(passedStudents)))
> dev.off()

pie chart bright

Creating Bar Chart

A new file named barchart.png will be created in your working directory. It contains the bar chart.


> subjects <- c ('English', 'Math', 'Science') # labels
> passedStudents <- c (33, 25, 21) # values
> png (file = 'barchart.png')
> barplot(passedStudents, names.arg = subjects, xlab = 'Subjects', ylab = 'Marks', col = 'blue', main = 'Passed Students')
> dev.off()

bar chart

Creating Line Graphs

A new file named linechart.png will be created in your working directory. It contains the line chart with two lines.


> male <- c(22, 34, 26, 32, 39)
> female <- c(33, 22, 33, 23, 35)
> png(file = 'linechart.png')
> plot(male, type = 'o', col = 'red', xlab = 'Class Room', ylab = 'Number of Students', main = 'Students')
> lines(female, type = 'o', col = 'blue')
> dev.off()

line chart

Hope this helps. Thanks.