R Plots Examples

Posted on by admin

How to create line and scatter plots in R. Examples of basic and advanced scatter plots, time series line plots, colored charts, and density plots. Building AI apps or dashboards in R? Deploy them to Dash Enterprise for hyper-scalability and pixel-perfect aesthetic.

  • Example 1: Overlay Multiple Densities in R. This Example illustrates how to overlay multiple numeric distributions in the same graphic in the basic installation of the R programming language. For this task, we need to apply the plot, lines, and density functions as shown below. Note that the first density needs to be created using the plot.
  • In the simplest case, we can pass in a vector and we will get a scatter plot of magnitude vs index. But generally, we pass in two vectors and a scatter plot of these points are plotted. For example, the command plot(c(1,2),c(3,5)) would plot the points (1,3) and (2,5). Here is a more concrete example where we plot a sine function form range -pi.
  • R Tutorial
  • R Data Interfaces
  • R Charts & Graphs
  • R Statistics Examples
  • R Useful Resources
  • Selected Reading

R Plot Examples


A line chart is a graph that connects a series of points by drawing line segments between them. These points are ordered in one of their coordinate (usually the x-coordinate) value. Line charts are usually used in identifying the trends in data.

The plot() function in R is used to create the line graph.

Syntax

The basic syntax to create a line chart in R is −

Following is the description of the parameters used −

R Plots Examples
  • v is a vector containing the numeric values.

  • type takes the value 'p' to draw only the points, 'l' to draw only the lines and 'o' to draw both points and lines.

  • xlab is the label for x axis.

  • ylab is the label for y axis.

  • main is the Title of the chart.

  • col is used to give colors to both the points and lines.

Example

A simple line chart is created using the input vector and the type parameter as 'O'. The below script will create and save a line chart in the current R working directory.

Plots

When we execute the above code, it produces the following result −

Line Chart Title, Color and Labels

The features of the line chart can be expanded by using additional parameters. We add color to the points and lines, give a title to the chart and add labels to the axes.

Example

When we execute the above code, it produces the following result −

Multiple Lines in a Line Chart

More than one line can be drawn on the same chart by using the lines()function.

After the first line is plotted, the lines() function can use an additional vector as input to draw the second line in the chart,

When we execute the above code, it produces the following result −

An effective and accurate data visualization is an important part of a statistical analysis. It can make your data come to life and convey your message in a powerful way.

R has very strong graphics capabilities that can help you visualize your data.

The plot() function

Plotting with r

In R, the base graphics function to create a plot is the plot() function. It has many options and arguments to control many things, such as the plot type, labels, titles and colors.

Syntax

The syntax for the plot() function is:

plot(x,y,type,main,xlab,ylab,pch,col,las,bty,bg,cex,)

Parameters

The plot() function arguments
ParameterDescription
xThe coordinates of points in the plot
yThe y coordinates of points in the plot
typeThe type of plot to be drawn
mainAn overall title for the plot
xlabThe label for the x axis
ylabThe label for the y axis
pchThe shape of points
colThe foreground color of symbols as well as lines
lasThe axes label style
btyThe type of box round the plot area
bgThe background color of symbols (only 21 through 25)
cexThe amount of scaling plotting text and symbols
Other graphical parameters

Create a Simple Plot

To get started with plot, you need a set of data to work with.

Let’s consider the built-in pressure dataset as an example dataset. It contains observations of the vapor pressure of mercury over a range of temperatures.

Line Plot In R

To create a plot just specify the dataset in plot() function.

Change the Shape and Size of the Points

You can use the pch (plotting character) argument to specify symbols to use when plotting points.

Here’s a list of symbols you can use.

For symbols 21 through 25, you can specify border color using col argument and fill color using bg argument.

To alter the size of the plotted characters, use cex (character expansion) argument.

Changing the Color

You can change the foreground color of symbols using the argument col.

R has a number of predefined colors that you can use in graphics. Use the colors() function to get a complete list of available names for colors.

Or you can refer the following color chart.

You can specify colors by index, name, hexadecimal, or RGB value. For example col=1, col='white', and col='#FFFFFF' are equivalent.

Different Plot Types

You can change the type of plot that gets drawn by using the type argument.

Here’s a list of all the different types that you can use.

Plot Types in R
ValueDescription
“p”Points
“l”Lines
“b”Both points and lines
“c”The lines part alone of “b”
“o”Both points and lines “overplotted”
“h”Histogram like (or high‐density) vertical lines
“s”Step plot (horizontal first)
“S”Step plot (vertical first)
“n”No plotting

For example, to create a plot with lines between data points, use type='l'; to draw both lines and points, use type='b'.

A series of graphics showing different types is shown below.

Adding Titles and Axis Labels

You can add your own title and axis labels easily by specifying following arguments.

ArgumentDescription
mainMain plot title
xlabx-axis label
ylaby-axis label

The Axes Label Style

By specifying the las (label style) argument, you can change the axes label style. This changes the orientation angle of the labels.

R Plot Graph

ValueDescription
0The default, parallel to the axis
1Always horizontal
2Perpendicular to the axis
3Always vertical

For example, to change the axis style to have all the axes text horizontal, use las=1

The Box Type

Plots

Specify the bty (box type) argument to change the type of box round the plot area.

ValueDescription
“o”(default) Draws a complete rectangle around the plot.
“n”Draws nothing around the plot.
“l”, “7”, “c”, “u”, or “]”Draws a shape around the plot area.

Add a Grid

The plot() function does not automatically draw a grid. However, it is helpful to the viewer for some plots. Call the grid() function to draw the grid once you call the plot().

Add a Legend

You can include a legend to your plot – a little box that decodes the graphic for the viewer. Call the legend() function, once you call the plot().

The position of the legend can be specified using the following keywords : “bottomright”, “bottom”, “bottomleft”, “left”, “topleft”, “top”, “topright”, “right” and “center”.

The effect of using each of these keywords is shown below.

Add Points to a Plot

You can add points to a plot with the points() function.

For example, let’s create a subset of pressure containing temperatures greater than 200 °C and add these points to the plot.

Add Lines to a Plot

You can add lines to a plot in a very similar way to adding points, except that you use the lines() function to achieve this.

You can change the line type using lty argument; and the line width using lwd argument.

Plotting with r

Here’s a list of line types you can use.

There’s another function called abline() which allows you to draw horizontal, vertical, or sloped lines.

Label Data Points

Use the text() function to add text labels at any position on the plot.

The position of the text is specified by the pos argument. Values of 1, 2, 3 and 4, respectively places the text below, to the left of, above and to the right of the specified coordinates.

Set Axis Limits

By default, the plot() function works out the best size and scale of each axis to fit the plotting area. However, you can set the limits of each axis quite easily using xlim and ylim arguments.

Display Multiple Plots on a Single Page

By using the mfrow graphics parameter, you can display multiple plots on the same graphics page.

To use this parameter, you need to pass a two-element vector, specifying the number of rows and columns. Then fill each cell in the matrix by repeatedly calling plot.

For example, mfrow=c(1, 2) creates two side by side plots.

Once your plot is complete, you need to reset your par() options. Otherwise, all your subsequent plots will appear side by side.

Save a Plot to an Image File

To save a plot to an image file, you have to do three things in sequence:

  • Call a function to open a new graphics file, such as png(), jpg() or pdf().
  • Call plot() to generate the graphics image.
  • Call dev.off() to close the graphics file.

myPlot.png

Remember that the file will be saved to your current working directory, unless you specify an absolute file path.