UNIT 5 R
UNIT 5 R
UNIT 5
Advanced Graphics in R
Plots in R:
In R language plots can be created y using different
commands. These commands can be basically classified into
high level and low level commands.
High Level plot commands in R:
Commands which create a new graph or plots are called
as high level plot commands. Here are some high level plot
Plot NC
commands.
Function Description
Scatter/ line plot
NM
Hist histogram
Barplot barplot
Box plot boxplot
Qnorm Normal-quantile
SR
1. plot()
In R language, basic plots can be created by using the
function plot().
The basic syntax of the function is as follows:
Plot(x,y)
Here, x represents the values for x-axis and y represents
values for y-axis.
1. Along with x and y we can pass many graphical
Vasudha GS, SRNMNC, ShimogaPage 1
UNIT 5
NC
2. main, xlab, ylab Options to include plot title, the horizontal
axis label, and the vertical axis label, respectively.
3. col Color (or colors) to use for plotting points and lines.
NM
4. pch Stands for point character . This selects which
character to use for plotting individual points.
6. lty Stands for line type . This specifies the type of line to
use to connect the points (for example, solid, dotted, or
dashed).
8. xlim, ylim This provides limits for the horizontal range and
vertical range (respectively) of the plotting region.
Plot Types:
By default, the plot function will plot individual points.
To control the plot type, you can specify a single character
valued option for the argument type.
The default value for type is "p", which can be interpreted
as “points only.”
type="l" means “lines only”.
Option "b" is used for both points and lines
"o" for over plotting the points with lines (this eliminates
NC
the gaps between points and lines visible for type="b").
The option type="n" results in no points or lines plotted,
creating an empty plot, which can be useful for
NM
complicated plots that must be constructed in steps.
Color:
While creating plots, we can specify colors . Specifying
colors makes the graph clearer.
Color can be added to the plots using the parameter col in
SR
plot(x,y,main="example",xlab="x",ylab="y",col=2)
NC
plot(x,y, main=”example”,xlab=”x”,ylab=”y”, col=”red”)
NM
SR
NC
NM
The lty parameter, which affects the type of line drawn,
SR
can
Take the values 1 through 6.
The following graph shows different types of lines for
each integer between 1-6.
NC
Low level commands:
Low-level plotting functions allow you to add elements, like points, or
lines, to an existing plot. Here are the most common low-level plotting
functions:
NM
Points Adds points to existing graph
Lines Adds line to existing plot
Text Adds text to existing plot
Legend Adds legends to existing graph
SR
1. point
points() function in R Language is used to add a group of points of
specified shapes, size and color to an existing plot.
Syntax:
points(x, y, cex, pch, col)
Here, x, y: Vector of coordinates,
cex: size of points
pch: shape of points
col: color of points
Vasudha GS, SRNMNC, ShimogaPage 6
UNIT 5
Example:
# R program to add points to a plot
# Creating coordinate vectors
x <- c(1.3, 3.5, 1.4, -3.1, 5.7, 2.4, 3.3, 2.5, 2.3, 1.9, 1.8, 2.3)
y <- c(2.5, 5.8, 2.1, -3, 12, 5, 6.2, 4.8, 4.2, 3.5, 3.7, 5.2)
plot(x, y, cex = 1, pch = 3, xlab ="x", ylab ="y", col ="black")
# Creating coordinates to be added
x2 <- c(4.2, 1.2, -2.4, -0.3, -1.3, 2.5)
y2 <- c(2.4, 4.3, 1.4, 2.3, -2, 4.5)
NC
# Calling points() function
points(x2, y2, cex = 2, pch = 6, col ="blue")
NM
Output:
SR
Here, point with ‘+’ symbol are added with plot() function and points
with triangle shape are added using points() function.
2. lines
lines() function in R Programming Language is used to add lines of
different types, colors and width to an existing plot.
Syntax:
lines(x, y, col, lwd, lty)
here, x, y: Vector of coordinates,
col: Color of line
NC
lwd: Width of line
lty: Type of line
Example program:
# R program to add lines into plots
NM
# Creating coordinate vectors
x <- c(1.3, 3.5, 1.4, -3.1, 5.7,
2.4, 3.3, 2.5, 2.3, 1.9, 1.8, 2.3)
y <- c(2.5, 5.8, 2.1, -3, 12, 5,
6.2, 4.8, 4.2, 3.5, 3.7, 5.2)
# Plotting the graph
SR
Output:
The
NC
Abline()
R function abline() can be
add vertical, horizontal or regression lines to a graph.
Syntax of the function is as follows:
used to
NM
abline(a=, b=, h=, v=, ...)
Here, a, b : single values specifying the intercept and the slope of the line
h : the y-value(s) for horizontal line(s)
v : the x-value(s) for vertical line(s)
Example Program:
SR
x=(1:10)
plot(x)
abline(h=4)
Output:
NC
3. text()
Text is defined as a way to describe data related to graphical
NM
representation. They work as labels to any pictorial or graphical
representation. In R language text to the plot can be added using text()
and mtext() functions.
Syntax:
text(x, y, labels)
SR
Output:
NC
Mtext()
NM
mtext() function in R Programming Language is used to add text to the
margins of the plot.
Synatx:
mtext(text, side)
Here, text: text to be written
SR
side: An integer specifying the side of the plot, such as: bottom, left, top,
and right.
Example Program:
# Create a scatter plot
x<-c(10,20,30,40,50)
y<-c(50,100,150,200,250)
plot(x,y, main = "Scatter Plot", xlab = "Speed", ylab = "Distance")
Output:
NC
NM
SR
4. Legends
Legends are useful to add more information to the plots and enhance
the user readability. It involves the creation of titles, indexes, placement
of plot boxes in order to create a better understanding of the graphs
plotted. The in-built R function legend() can be used to add legend to
plot.
Syntax:
legend(x, y, legend, fill, col, bg, lty, cex, title, [Link], bg)
Here, x and y: These are co-ordinates to be used to position the
legend
legend: Text of the legend
fill: Colors to use for filling the boxes of legend text
col: Colors of lines
bg: It defines background color for the legend box.
title: Legend title (optional)
plot(x, y, col="blue")
# adding another line on the
# coordinates involving y and z
lines(z, y ,col="red")
# Adding a legend to the graph
# defining the lines
legend(2, 4, legend=c("Equation 1", "Equation 2"), fill = c("blue","red") )
Output:
NC
NM
Graphics parameters:
In R programming language we can customize the appearance of
plots. There are a variety of graphical parameters that can be used to do
so. Some of the most commonly used graphical parameters include:
xlim and ylim: These parameters set the limits of the x and y axes,
SR
NCthe size of elements in the plot, such as points or text. cex takes a
numeric value with, 1 being the default size.
Local and global parameters:
Local graphical parameters in R have specific to a particular plot
NM
and set within the plot function .
For example, the parameters like main, cex, xlab, ylab etc
specified inside plotting function.
These parameters affect only the appearance of current graph and
do not affect other plots in the session.
SR
NC
6. lend—this sets line end style, specifying how the ends of lines
should be drawn. It can take one of these values. “Round”
or “square”
par(lend = "square")
, “butt”
NM
7. col –this can be used as local parameter and global parameter.
When used with par() function , it will set color for all the
subsequent plots.
[Link] and lwd-- these can be used as local parameter and global
parameter. When used with par() function , they will set line type
SR
1. Screen Device:
When we call the function plot(), it considers console
screen as the destination for the plot,
Plot(x,y) –this statement creates and displays a plot on the
screen on active window.
We can display multiple plots on the screen at the same time
, without affecting each other, we can create multiple
devices or active windows by using the function [Link]().
When we create devices using [Link](), each created
windows will be assigned integers in the order of their
NC creation.
[Link]() creates a new window and sets it as a active window.
Example:
x1<-1:5
NM
y1 <-6:10
x2<-1:5
y2 <-6:10
plot(x1,y1)
[Link]()
SR
plot(x2,y2)
[Link]()
Here, the first plot will be created on the active window. Then we
are creating a new active device by using [Link](), and the
second plot will be displayed on the newly created active
window/device.
When we create a device by using [Link](), it should be closed by
using [Link]() after its purpose is served.
When we have multiple active devices/ windows , we can switch
NC
window. To shift to first window, we can write [Link](1).
Multiple plots In One device.
It is also possible to display multiple plots on a single device/ or
window.
NM
This is done by dividing the window area into rows and columns.
The function par() takes a parameter “mfrow” for number of
rows and columns into which window should be divided.
Example:
# Set up a 2x2 layout (2 rows, 2 columns)
SR
Output:
NC
NM
The layout() function in R provides a flexible way to arrange
multiple plots in a customized layout. It allows you to specify the
SR
number of rows and columns, and you can define a matrix that
describes the placement of individual plots within those rows and
columns.
Example program:
# Define the layout structure (2 rows, 2 columns)
layout_matrix <- matrix(c(1, 2, 3, 4), nrow = 2, byrow = TRUE)
NC
Output:
NM
SR
NC
that make up the image.
The plot region is all you’ve dealt with so far. This is where your
actual
plot appears and where you’ll usually be drawing your points, lines,
NM
text, and so on.
The plot region uses the user coordinate system , which reflects
the value and scale of the horizontal and vertical axes.
The figure region is the area that contains the space for your axes,
their labels, and any titles. These spaces are also referred to as the
SR
figure margins .
The outer region, also referred to as the outer margins , is
additional space around the figure region that is not included by
default but can be specified if it’s needed.
Default Spacing:
We can check the default margin setting of the figure region by
using the function par() with oma and mar.
Oma display the default values of outer margin region and mar
shows margin settings.
par()$oma
Vasudha GS, SRNMNC, ShimogaPage 21
UNIT 5
NC
x <- 1:10
y <- x^2
# Create a scatter plot with default margins
plot(x, y, main = "Default Margins")
# Customize margins using par()
NM
par(mar = c(5, 4, 4, 2) + 0.1) # Setting margins: bottom, left, top, right
# Create a scatter plot with customized margins
plot(x, y, main = "Customized Margins")
# Reset margins to default values
par(mar = c(5, 4, 4, 2) + 0.1) # Resetting to default values
In the par() function, the mar argument sets the margins. The order of
SR
values in the vector corresponds to the bottom, left, top, and right
margins, respectively. These Values can be adjusted according to our
requirement.
Alternatively, we can use the oma (outer margin) parameter in the par()
function to set the outer margins, which include the main title and axis
labels.
Clipping:
Controlling clipping allows you to draw in or add elements to the
NC
x <- 1:10
y <- x^2
# Set xpd to FALSE to restrict plotting to the inside of the plotting region
par(xpd = FALSE)
SR
In this example, when xpd is set to FALSE, attempting to plot outside the
specified clipping region will not produce any output. Resetting xpd to
TRUE allows plotting outside the plotting region again.
NC
Adding Box around plot:
The box() function is often used to add a box around the
plot area. You can customize the appearance of the box
using the lwd (line width) and col (color) parameters.
NM
# Create a scatter plot
plot(1:10, 1:10, xlab = "X-axis", ylab = "Y-axis", main = "Box
Example")
# Add a box around the plot area
SR
This example adds a red box with a line width of 2 around the
plot area.
Output:
NC
Along with above specified arguments, box can take
another parameter, bty which indicates the type of box.
The bty argument is supplied a single character: "o"
NM
(default), "l", "7", "c", "u", "]", or "n". the resulting box
boundaries will follow the appearance of the
corresponding uppercase letter.
Customizing Axes:
SR
Here,NC
NM
side: Specifies which side of the plot the axis should be
drawn on. Possible values are 1 (bottom), 2 (left), 3 (top),
4 (right).
at: A numeric vector specifying the positions of tick marks.
labels: Logical value indicating whether tick labels should
SR
be drawn.
tick: Logical value indicating whether tick marks should be
drawn.
line: The line type of the axis line. If NA, no axis line is
drawn.
pos: The position of the axis line relative to the plotting
region.
outer: Logical value indicating whether the axis should be
NC
elements such as plot titles, axis labels, tick labels, legends,
and annotations. Below are examples demonstrating how to
customize fonts in R plots using the par() function and other
plotting functions.
NM
1. Customizing Fonts in the Entire Plot:
You can use the par() function to set graphical parameters for
the entire plot, including font-related parameters.
Example:
SR
# Sample data
x <- 1:10
y <- x^2
# Set graphical parameters for the entire plot
par(family = "serif", [Link] = 2, [Link] = 1.5)
# Create a scatter plot
plot(x, y, main = "Custom Font")
NC
y <- x^2
# Create a scatter plot with customized font
plot(x, y, main = "Custom Font", xlab = "X-axis Label", ylab = "Y-
axis Label", [Link] = "blue", [Link] = 1.2)
NM
Here, xlab and ylab parameters allow you to set the labels
for the x and y-axes.
[Link] = "blue" sets the color of the axis labels to blue.
SR
NC
Histograms:
A histogram contains a rectangular area to display the
statistical information which is proportional to the frequency of
NM
a variable and its width in successive numerical intervals. A
graphical representation that manages a group of data points
into different specified ranges. It has a special feature that
shows no gaps between the bars and is similar to a vertical bar
graph.
SR
Syntax:
hist(v, main, xlab, xlim, ylim, breaks, col, border)
Here,
v: This parameter contains numerical values used in
histogram.
main: This parameter main is the title of the chart.
col: This parameter is used to set color of the bars.
xlab: This parameter is the label for horizontal axis.
Vasudha GS, SRNMNC, ShimogaPage 29
UNIT 5
NC
# Create the histogram.
hist(v, xlab = "[Link] Articles ",
col = "green", border = "black")
NM
Output:
SR
Pie chart:
A pie chart is a circular statistical graphic, which is divided into
slices to illustrate numerical proportions. It depicts a special
chart that uses “pie slices”, where each sector shows the
relative sizes of data. A circular chart cuts in the form of radii
into segments describing relative frequencies or magnitude
also known as a circle graph.
R Programming Language uses the function pie() to create pie
NC
charts. It takes positive numbers as a vector input.
Syntax:
NM
pie(x, labels, radius, main, col, clockwise)
Here,
x: This parameter is a vector that contains the numeric
values which are used in the pie chart.
labels: This parameter gives the description to the slices
SR
in pie chart.
radius: This parameter is used to indicate the radius of the
circle of the pie chart.(value between -1 and +1).
main: This parameter is represents title of the pie chart.
clockwise: This parameter contains the logical value
which indicates whether the slices are drawn clockwise or
in anti clockwise direction.
col: This parameter give colors to the pie in the graph.
Vasudha GS, SRNMNC, ShimogaPage 31
UNIT 5
Example program:
# Create data for the graph.
geeks<- c(23, 56, 20, 63)
labels <- c("Mumbai", "Pune", "Chennai", "Bangalore")
# Plot the chart.
pie(geeks, labels)
Output:
NC
NM
SR
Bar Chart:
Bar charts are a popular and effective way to visually represent
categorical data in a structured manner. R stands out as a
powerful programming language for data analysis and
visualization.
R uses the barplot() function to create bar charts. Here, both
vertical and Horizontal bars can be drawn.
Here,
H: This parameter is a vector or matrix containing numeric
values which are used in bar chart.
xlab: This parameter is the label for x axis in bar chart.
ylab: This parameter is the label for y axis in bar chart.
main: This parameter is the title of the bar chart.
[Link]: This parameter is a vector of names appearing
Output:
NC
NM
Creating a Horizontal Bar Chart in R
To create a horizontal bar chart:
1. Take all parameters which are required to make a simple
bar chart.
SR
NC
Scatter plot In R:
NM
A scatter plot is a set of dotted points representing individual
data pieces on the horizontal and vertical axis. In a graph in
which the values of two variables are plotted along the X-axis
and Y-axis, the pattern of the resulting points reveals a
SR
NC
x <- c(1, 2, 3, 4, 5)
y <- c(2, 4, 1, 7, 3)
# Create scatter plot
plot(x, y, main = "Simple Scatter Plot", xlab = "X-axis", ylab = "Y-axis")
NM
output:
SR
Scatterplot Matrices
When we have two or more variables and we want to correlate
between one variable and others so we use a R scatterplot
matrix.
pairs() function is used to createR matrices of scatterplots.
Here,
NC
Syntax:
pairs(formula, data)
Output:
NC
NM
3D Scatterplots
SR
NC
Scatter Plot", xlab = "X-axis", ylab = "Y-axis", zlab = "Z-axis")
NM
SR