R Graphics Devices

Learn everything about R graphics devices—types, default behavior, and best choices for saving high-quality plots. Discover key functions like abline() for adding reference lines and hovplot() in the HH package for effect analysis. This R Graphics Devices guide covers multiple methods to save graphs (PNG, PDF, SVG) and answers FAQs for R users. Perfect for beginners and experts on RFAQs.com!

What are R Graphics Devices?

The R graphics devices are interfaces or engines that handle the rendering and output of graphical plots and charts. These R graphics devices determine where and how visualizations are displayed: whether on-screen or saved to a file (e.g., PNG, PDF, SVG).

What are the Types of R Graphics Devices?

R Language supports multiple graphics devices, and is divided into two main categories:

On-Screen (Interactive) Devices

These display plots in an interactive window:

  • windows(): Default on Windows (opens a new graphics window).
  • quartz(): Default on macOS.
  • X11(): Default on Linux/Unix.
  • RStudioGD(): The device used in RStudio’s “Plots” pane.

File-Based (Non-Interactive) Devices

These save plots to files in various formats:

  • win.metafile(): (Windows only) – Windows Metafile vector format.
  • pdf(): Saves plots as PDF (vector format, scalable).
  • png() / jpeg() / tiff(): Raster image formats (pixel-based).
  • svg() / cairo_svg(): Vector-based SVG format (scalable).
  • bmp(): Bitmap image format.
  • postscript(): EPS/PS vector format (older standard).
R Graphics Devices

What is the default behaviour of R Graphics Devices?

  • If no device is open, R automatically opens an on-screen device (e.g., RStudioGD in RStudio).
  • If you call a plotting function (like plot(). It sends output to the currently active device.

Which R Graphics Devices Should One Use?

  • For interactive viewing: Default on-screen device (e.g., RStudio’s plot pane)
  • For high-quality, scalable graphics (publications): pdf(), svg()
  • For web/online use: png(), jpeg()

How many methods are there to save graphs in R?

In R, there are multiple methods to save graphs, depending on whether one is using Base R, ggplot2, or other plotting systems

  1. Using Base R Graphics Devices: The most common approach is to use graphics devices to save plots to files (such as pdf(), png(), jpeg(), tiff(), bmp(), svg(), postscript(), win.metafile()). The already completed plot on-screen can be saved without re-running the code.
  2. Using ggplot2: The ggplot2 is a preferred modern method to save plots. It automatically detects format from the extension (.png, .pdf, .svg, etc.), allows adjusting DPI (resolution) and dimensions easily, and works seamlessly with ggplot2 objects.
  3. Using RStudio’s GUI: RStudio displays the plot in the ‘Plots Pane’.
  4. Using grid and lattice Graphics: The grid-based plots (including lattice) can be saved using a graphics device.
  5. Using Cairo: For High-Quality Anti-Aliased Graphics: For better quality (such as for publications), use the Cairo package.
MethodBest ForCode Example
pdf(), png(), etc.Base R plotspdf("plot.pdf"); plot(); dev.off()
dev.copy()Quick saves after plottingdev.copy(png, "plot.png"); dev.off()
ggsave()ggplot2 plotsggsave("plot.png", p)
RStudio GUI ExportManual savingNo code (click “Export”)
Cairo packageHigh-quality exportsCairoPNG("plot.png")

What is the use of abline() function?

The abline() function in R is used to add straight lines (horizontal, vertical, or regression) to an existing plot. It is a versatile function that helps in enhancing data visualizations by adding reference lines, trendlines, or custom lines.

What are the Key uses of abline()?

  1. Add Horizontal or Vertical Lines
  2. Add Regression Lines (Best-Fit Lines)
  3. Add Lines with Custom Slopes and Intercepts
  4. Add Grid Lines or Axes

Describe the Arguments in abline()

ArgumentPurposeExample
hY-value for horizontal lineabline(h = 5)
vX-value for vertical lineabline(v = 3)
aIntercept (y at x=0)abline(a = 1, b = 2)
bSlopeabline(a = 1, b = 2)
regLinear model objectabline(lm(y ~ x))
colLine colorabline(col = "red")
ltyLine type (1=solid, 2=dashed, etc.)abline(lty = 2)
lwdLine width (thickness)abline(lwd = 2)

What is hovplot() in HH Package?

The hovplot() function is part of the HH package in the R language, which is designed for statistical analysis and visualization, particularly for ANOVA and regression diagnostics. The hovplot() function specifically creates “Half-Normal Plots with Overlaid Simulation”, a graphical tool used to assess the significance of effects in experimental designs (e.g., factorial experiments).

Try Development Economics MCQs Test

R Graphics Devices

Using ggplot2 in R Language

Introduction to using ggplot2 in R Language

ggplot2 is a popular R package that provides flexible and elegant grammar of graphics for creating a wide range of dynamic and static graphics. It breaks down plots into fundamental components like data, aesthetics, geometric objects, and statistical transformations. In this post, we will learn about using ggplot2 in R Language.

There are three strategies for plotting in R language.

  1. base graphics using functions such as plot(), points(), and par()
  2. lattice graphics to create nice graphics, however, it is not easy to create high-dimensional data graphics.
  3. ggplot package, it is an implementation of “Grammar of Graphics”.

The ggplot2 is built on the principle of layering graphical elements, making it flexible and customizable.

To plot using ggplot2 in R Langauge, a data.frame object is required as an input, then one needs to define plot layers that stack on top of each other, and each layer has visual/text elements that are mapped to aesthetics (size, colors, and opacity). An extremely informative graph will be produced using the above-described simple set of commands.

Before drawing high-quality informative graphs, one needs to install the ggplot2 package. If ggplot2 is already installed, one does not need to reinstall it using the command below.

install.packages("ggplot2")

Scatter Plot using ggplot2 in R

Let us draw a dot plot (scatter points) graph between variables $hp$ (horsepower) and $disp$ (displacement) from mtcars dataset.

# first load the data set say mtcars
attach(mtcars)

# load the ggplot2 library
library(ggplot2)

# now specify the dataset and variables
p <- ggplot(mtcars, aes(x = disp, y = hp))

# Add a plot layer with points
p <- p + geom_point()
print(p) # display/ show the plot
using ggplot2 in R Language

Note that geom, aesthetics, and facets are three important concepts in drawing the graphs using ggplot2, where

  • geom is the type of the plot
  • aesthetics is the shape, color, size, and alpha values used in ggplot
  • facet are small multiples, displaying different subsets of data

When certain aesthetics are defined, an appropriate legend is chosen and displayed automatically.

p <- ggplot(mtcars, aes(x = disp, y = hp))
p <- p + geom_point(aes(color = mpg))
p
using ggplot2 in R with aesthetics

Updating Graphs using aesthetics (color, size, and shape)

Graphs can be updated by assigning variables to aesthetics color, size, and shape. For example

p <- ggplot(mtcars, aes(x = disp, y = hp))
p <- p + geom_point(aes(color = gear, size = wt))
p
Using ggplot2 in R scatter plot with more aesthetics

Consider the following example. Here, the $gear$ variable is taken as a factor (grouping variable).

p <- ggplot(mtcars, aes(x = disp, y = hp))
p <- p + geom_point(aes(color = as.factor(gear), size = wt))
p
ggplot2

Note that the behaviour of the aesthetics is predictable and customizable.

AestheticDiscrete VariableContinuous Variable
colorRainbow of colorsGradient from red to blue
sizeDiscrete size stepsLinear mapping between radius and value
shapeDifferent shapes for each groupShould not work

Faceting in ggplot2

A small multiple (sometimes called faceting, trellis chart, lattice chart, panel chart, or grid chart) is a series or grid of small similar graphics or charts for comparison purposes. Usually, these small multiples are used to display different subsets of the data and these multiples are useful for exploring some conditional relationship between variables (especially when data is large enough).

Let us examine the faceting of different types. The following are some examples of subsetting the scatterplot in facets

# Create a basic scatter plot
p <- ggplot(mtcars, aes(x = disp, y = hp))
p <- p + geom_point()

# columns are cyl categories
p1 <- p + facet_grid(. ~ cyl)

# rows are cyl categories
p2 <- p + facet_grid(cyl ~ .)

# columns and rows both
p3 <- p + facet_grid(carb ~.)

wrap plots by cyl
p4 <- p + facet_grid(~ am)

# plot all four in one 
library(gridExtra)
grid.arrange(grobs = list(p1, p2, p3, p4), ncol = 2, top = "Facet Examples")
using ggplot2 in R using facets

https://itfeature.com

https://gmstat.com

Graphical Representations in R

Many graphical representations in R Language are available for qualitative and quantitative data types. This post will only discuss graphical representations in R such as histograms, bar plots, and box plots.

Creating Histogram in R

To visualize a single variable, the histogram can be drawn using the hist() function in R. The use of histograms is to judge the shape and distribution of data in a graphical way. Histograms are also used to check the normality of the variable.

Let us attach the data from iris dataset.

attach(iris)
head(iris)
hist(Petal.Width)

We can enhance the histogram by using some arguments/parameters related to the hist() function in R. For example,

hist(Petal.Width,
  xlab = "Petal Width",
  ylab = "Frequency",
  main = "Histogram of Petal Width from Iris Data set",
  breaks = 10,
  col = "dodgerblue",
  border = "orange")
Graphical Representations in R Language

If these arguments are not provided, R will attempt to intelligently guess them, especially the number of breaks. See the YouTube tutorial for graphical representations of the histogram.

Creating Barplots in R

The bar plots are the best choice for visual inspection of a categorical variable (or a numeric variable with a finite number of values), or a rank variable. Usually, one can use bar plots for comparison purposes. The barplot() function can be used for visual inspection of a categorical variable.

library(mtcars)
barplot( table(cyl) )
barplot(table(cyl),
  ylab = "Frequency",
  xlab = "Cylinders (4, 6, 8)",
  main = "Number of cylinders ",
  col = "green",
  border = "blue")

Creating Boxplots in R

One can use Boxplots to visualize the normality, skewness, and existence of outliers in the data based on five-number summary statistics.

boxplot(mpg)
boxplot(Petal.Width)
boxplot(Petal.Length)

However, one can compare a numerical variable for different values of a categorical/grouping variable. For example,

boxplot(mpg ~ cyl, data = mtcars)
Graphical Representations in R Boxplot

The reads the formula mpg ~ cyl as: “Plot the mpg variable against the cyl variable using the dataset mtcars. The symbol ~ used to specify a formula in R.

boxplot(mpg ~ cyl, data =mtcars,
  xlab = "Cylinders",
  ylab = "Miles per Gallon",
  pch = 20,
  cex = 2,
  col = "pink",
  border = "black")
Graphical-representation-in-r

See How to perform descriptive statistics

Visit: MCQs and Quiz site https://gmstat.com