Unit 5 r Programming
Unit 5 r Programming
Display graphics
Other high-level graphics functions produce different
types of plots. Some examples are:
qqnorm(x)
qqline(x)
qqplot(x, y)
axis(side, …)
Mathematical annotation
In some cases, it is useful to add mathematical symbols
and formulae to a plot. This can be achieved in R by
specifying an expression rather than a character string
in any one of text, mtext, axis, or title. For example, the
following code draws the formula for the Binomial
probability function:
> text(x, y, expression(paste(bgroup("(", atop(n, x),
")"), p^x, q^{n-x})))
More information, including a full listing of the features
available, can be obtained from within R using the
commands:
> help(plotmath)
> example(plotmath)
> demo(plotmath)
Graphical elements
R plots are made up of points, lines, text, and polygons
(filled regions.) Graphical parameters exist that control
how these graphical elements are drawn, as follows:
pch="+"
Character to be used for plotting points. The
default varies with graphics drivers, but it is
usually a circle. Plotted points tend to appear
slightly above or below the appropriate position
unless you use "." as the plotting character, which
produces centered points.
pch=4
When pch is given as an integer between 0 and 25
inclusive, a specialized plotting symbol is
produced. To see what the symbols are, use the
command
> legend(locator(1), as.character(0:25), pch =
0:25)
Those from 21 to 25 may appear to duplicate
earlier symbols but can be colored in different
ways: see the help on points and its examples.
In addition, pch can be a character or a number in
the range 32:255 representing a character in the
current font.
lty=2
Line types. Alternative line styles are not
supported on all graphics devices (and vary on
those that do), but line type 1 is always a solid
line, line type 0 is always invisible, and line types 2
and onwards are dotted or dashed lines or some
combination of both.
lwd=2
Line widths. Desired width of lines, in multiples of
the “standard" line width. Affects axis lines as well
as lines drawn with lines(), etc. Not all devices
support this, and some have restrictions on the
widths that can be used.
col=2
Colors to be used for points, lines, text, filled
regions, and images. A number from the current
palette (see ?palette) or a named color.
col.axis
col.lab
col.main
col.sub
The color to be used for axis
annotation, x and y labels, main and sub-titles,
respectively.
font=2
An integer that specifies which font to use for text.
If possible, device drivers should be arranged to
correspond to plain text, 2 to boldface, 3 to
italic, 4 to bold italic, and 5 to a symbol font
(which includes Greek letters).
font.axis
font.lab
font.main
font.sub
The font to be used for axis
annotation, x and y labels, main and sub-titles,
respectively.
adj=-0.1
Justification of text relative to the plotting
position. 0 means left justify, 1 means right justify
and 0.5 means to center horizontally about the
plotting position. The actual value is the proportion
of text that appears to the left of the plotting
position, so a value of -0.1 leaves a gap of 10% of
the text width between the text and the plotting
position.
cex=1.5
Character expansion. The value is the desired size
of text characters (including plotting characters)
relative to the default text size.
cex.axis
cex.lab
cex.main
cex.sub
The character expansion to be used for axis
annotation, x and y labels, and main and sub-
titles, respectively.
Figure margins
A single plot in R is known as a figure and comprises
a plot region surrounded by margins (possibly
containing axis labels, titles, etc.) and (usually)
bounded by the axes themselves.
A typical figure is
Graphics parameters controlling figure layout include:
mai=c(1, 0.5, 0.5, 0)
Widths of the bottom, left, top and right margins,
respectively, are measured in inches.
mar=c(4, 2, 2, 1)
Similar to mai, except the measurement unit is
text lines.
mar and mai are equivalent in the sense that setting
one changes the value of the other. The default values
chosen for this parameter are often too large; the right-
hand margin is rarely needed, and neither is the top
margin if no title is being used. The bottom and left
margins must be large enough to accommodate the
axis and tick labels. Furthermore, the default is chosen
without regard to the size of the device surface: for
example, using the postscript() driver with
the height=4 argument will result in a plot that is about
50% margin unless mar or mai are set explicitly. When
multiple figures are in use (see below), the margins are
reduced. However, this may not be enough when many
figures share the same page.
library(plotly)
library(shiny)
library(plotly)
ui <- fluidPage(
titlePanel("Dynamic Scatter Plot"),
sidebarLayout(
sidebarPanel(
sliderInput("slider", "Select x-axis range:",
min = 0, max = 100, value = c(0, 100))
),
mainPanel(
plotlyOutput("scatterPlot")
)
)
)
shinyApp(ui, server)
This app will dynamically update the scatter plot based
on the slider input, allowing users to filter data by the
mpg variable.
3. ggplot2 with plotly – Combining Static and
Dynamic Graphics
ggplot2 is a widely used static plotting package in R,
but you can convert static ggplot2 plots into dynamic
interactive plots using the plotly library.
Example:
r
Copy code
# Install ggplot2 if you haven't already
# install.packages("ggplot2")
library(ggplot2)
library(plotly)
library(highcharter)
library(leaflet)
library(DT)
library(ggplot2)
# Example data
df <- data.frame(x = 1:10, y = (1:10)^2)
library(plotly)
# Customize layout
p <- p %>% layout(
title = "Interactive Plot with Plotly",
xaxis = list(title = "Miles Per Gallon (mpg)"),
yaxis = list(title = "Horsepower (hp)"),
showlegend = FALSE
)
# Display plot
p
Customization options in plotly:
marker – Customize the points, such as color, size,
and symbol.
layout() – Customize titles, axis labels, and
legends.
showlegend – Show or hide the legend.
hoverinfo – Customize the information shown when
hovering over points.
5. Customizing highcharter Plots
The highcharter package allows the creation of
interactive plots, which can be customized with colors,
tooltips, and more.
Example of Customizing a highcharter Plot:
r
Copy code
# Install highcharter if you haven't already
# install.packages("highcharter")
library(highcharter)
# Simple line chart with customization
highchart() %>%
hc_chart(type = "line") %>%
hc_add_series(data = c(1, 2, 3, 4, 5), name =
"Series1") %>%
hc_title(text = "Custom Highcharter Plot") %>%
hc_subtitle(text = "An interactive line chart") %>%
hc_xAxis(title = list(text = "X-Axis")) %>%
hc_yAxis(title = list(text = "Y-Axis")) %>%
hc_tooltip(headerFormat =
"<b>{series.name}</b><br>", pointFormat = "X:
{point.x}, Y: {point.y}")
Customization options in highcharter:
hc_title() and hc_subtitle() – Titles for the chart and
subtitle.
hc_xAxis() and hc_yAxis() – Axis labels and other
settings.
hc_tooltip() – Customizes the tooltip on hover.
6. Advanced Customizations:
For more advanced customizations, you can:
Adjust Color Palettes: Use custom color
schemes with scale_color_manual(),
scale_fill_manual(), or RColorBrewer for ggplot2.
Faceting: Use facet_wrap() or facet_grid() in
ggplot2 to create subplots based on categories.
Themes: Use pre-built themes or create custom
themes in ggplot2 to standardize the appearance
of your plots.
plotting regions and margin in r
In R, plotting regions and margins can be
customized to adjust the layout and spacing of your
plots, making them more visually appealing or better
suited to the data you're visualizing. These
customizations are primarily handled through the par()
function in base R, while for more complex layouts or
multi-plot arrangements, the mfrow or mfcol arguments
in par() can be used. For ggplot2 and interactive plots,
adjustments can be made as well.
1. Plotting Regions and Margins in Base R
Plotting Regions:
The plotting region refers to the area where the plot is
drawn. In base R, you can use par(mfrow = c(n, m)) or
par(mfcol = c(n, m)) to divide the plotting area into
multiple regions (subplots).
mfrow: Specifies the number of rows and columns
for the plotting layout.
mfcol: Specifies the number of rows and columns,
but plots are filled by columns rather than rows.
Example: Multiple Plots in One Window
r
Copy code
# Set up a 2x2 plotting grid (2 rows, 2 columns)
par(mfrow = c(2, 2))
# Plot 1
plot(1:10, 1:10, main = "Plot 1")
# Plot 2
plot(1:10, (1:10)^2, main = "Plot 2")
# Plot 3
plot(1:10, sqrt(1:10), main = "Plot 3")
# Plot 4
plot(1:10, log(1:10), main = "Plot 4")
# Base R histogram
hist(data,
main = "Histogram of Random Data", # Title
xlab = "Value", # X-axis label
col = "lightblue", # Bar color
border = "black", # Bar border color
breaks = 30, # Number of bins
freq = FALSE # Use density (TRUE
uses frequency counts)
)
ggplot2 Histogram:
r
Copy code
# Load ggplot2 package
library(ggplot2)
# Create data
data <- data.frame(value = rnorm(1000))
# ggplot2 histogram
ggplot(data, aes(x = value)) +
geom_histogram(binwidth = 0.5, fill = "skyblue", color
= "black", alpha = 0.7) +
labs(title = "ggplot2 Histogram", x = "Value", y =
"Frequency")
2. Bar Chart
A bar chart is typically used to represent categorical
data with rectangular bars.
Base R Bar Chart:
r
Copy code
# Sample data
categories <- c("A", "B", "C", "D")
values <- c(10, 15, 7, 25)
library(plotly)
# Sample data
x <- rnorm(100)
y <- rnorm(100)