Unit-4

 Data Visualization

Using the diverse functionalities provided by R, one can create visually appealing data visualizations with only a few lines of code. Data visualization is an efficient technique of gaining insights about data through a visual medium.

  • With the help of visualization techniques, humans can easily gain insights about the hidden patterns in data which might otherwise be neglected. 
  • Using data visualization, one can work with large datasets to efficiently obtain key insights about it. 

R Visualization Packages

Following are some of the essential visualization packages in R Programming:


The basics of the graphics

Key elements of a statistical graphic:

  • Data
  • Aesthetic Mappings
  • Geometric Objects
  • Statistical Transformations
  • Scales
  • Coordinates system
  • Faceting

Now, let us discuss each of them.

 Aesthetic Mappings

  • It controls the relation between data variables and graphics variables.
  • Also, it helps to map the temperature variable of a data set into the X variable in a scatter plot.
  • It helps to map the species of a plant into the colour of dots in graphics.

Geometric Objects

It shows each observation by a point using the aesthetic mappings that map two variables in the data set into the x,y variables of the plot.

Statistical Transformations

  • It allows us to calculate and also perform a statistical analysis of the data in the plot.
  • Also, the statistical transformation uses the data and approximates it by a regression line x,y coordinates.
  • It counts occurrences of certain values.

Scales

It maps the data values into values in the coordinate system of the graphics device.

Coordinate system

We use it to plot the data.

  • Cartesian
  • Plot

Faceting

It splits the data into subgroups and draws sub-graphs for each group.

1. Controlling the Line Properties of a Chart

Line properties are crucial aesthetic elements in visualizations, particularly for line charts, where they help differentiate categories, emphasize trends or denote time series. In ggplot2, control over line properties like color, size and pattern relies on the distinction between aesthetic mapping and static setting.

Propertyggplot2 AestheticValues (Examples)
Line Typeline type"solid", "dashed", "dotted", "twodash"
Line Thicknessline widthNumeric values (e.g., 0.5, 1.2, 2)
Line ColorcolorHex codes (#FF0000), R color names ("red")


A. Aesthetic Mapping for Data-Driven Variation

When a line property needs to vary based on a variable in the dataset (e.g., showing a different line type for each "Region"), the property is mapped inside the aes() function. This automatically generates a legend.

Example: Linking a data variable to a visual property.

Technique

R Implementation (ggplot2)

Purpose

Mapping Line Type

geom_line(aes(linetype = Group_Variable))

Differentiates groups by line pattern.

B. Manual Scaling for Explicit Control

To override R's default choices and assign specific line properties to the groups, manual scale functions are added as layers to the plot.

Example: Overriding the default visual assignments generated by ggplot2 for mapped aesthetics.

TechniqueR Implementation (ggplot2)Example
Manual Line Typescale_linetype_manual(values = c(...))+ scale_linetype_manual(values = c("dotted", "twodash"))

Example-

Suppose x=c(1,2,3,4,5)

                y=c(1,4,9,16,25)

plot(x, y, type = "o", col = "blue", lty = 2, lwd = 2, pch = 17, cex = 1.5,

     main = "Line Properties Example", xlab = "X-axis", ylab = "Y-axis")

Where: 

  • col: Line color ("red", "blue", "#FF5733" for hex colors).
  • lty: Line type (1 for solid, 2 for dashed, etc.).
  • lwd: Line width.
  • pch: Point type (16 for filled circles, 17 for triangles, etc.).
  • cex: Marker size.

Output:

2. Using Keyword Arguments for Direct Static Styling

In ggplot2, "keyword arguments" are used for direct styling or static control of visual properties. This means setting a property to a constant value that applies to all elements within that geometric layer, irrespective of the data.

Example: Setting a property value outside the aes() function to apply a consistent style across the entire layer. This is used when the property does not need to be tied to a specific data variable and thus, no legend is generated.

Keyword ArgumentPlacementPurposeExample
Static ColorOutside aes() in geom_*Sets a single color for all geometric elements in that layer.geom_line(color = "blue")
Static SizeOutside aes() in geom_*Sets a single thickness for all lines or size for all points.geom_line(linewidth = 1.5)


In R: (Keyword arguments set properties statically)

ggplot(data, aes(x = Time, y = Value)) +

          geom_line(color = "red", linewidth = 1.2) 

Example:

Suppose x=c(1,2,3,4,5)

                y=c(1,4,9,16,25)

plot(x, y, type = "o", col = "darkgreen", lty = 1, lwd = 3, pch = 19,

     main = "Keyword Arguments Example", xlab = "X-axis", ylab = "Y-axis")

Here, the keyword arguments (type, col, lty, etc.) are directly passed to the plot() function.


3. Using the Setter Methods

The concept of explicit setter methods (e.g., ax.set_title(), ax.set_xlabel()) is characteristic of the Object-Oriented (OO) plotting approach used in systems like Python's matplotlib. R's ggplot2 adopts a declarative, additive approach known as the Grammar of Graphics, where configuration is achieved by adding specific function layers, not by calling methods on an axis object.

Example: In ggplot2, the functionality of setters is replaced by adding specific non-data layers using the + operator.

Conceptual Setter Methodggplot2 R Equivalent (Additive Layer)Purpose
Setting Title/Labelslabs()Replaces set_title(), set_xlabel(), etc., for setting text labels.
Setting Plot Style/Themetheme()Used for granular control over non-data elements (e.g., background, font size, grid lines).


In R-

# p is the plot object

p <- ggplot(data, aes(x = Month, y = Sales)) + geom_line()

# 1. Setting Labels (Equivalent to set_title, set_xlabel)

p <- p + labs(title = "Monthly Sales Report",

              x = "Time Period",

              y = "Total Revenue")

# 2. Setting Theme/Style (Equivalent to bulk style setters)

      p <- p + theme_minimal() +         # Use a built-in theme

     theme(plot.title = element_text(face = "bold", size = 16)) # Custom                                                                                                                                   styling

Example-

par(col = "purple", lty = 3, lwd = 2)  # Set default line properties

plot(x, y, type = "o", main = "Setter Methods Example")


4. Using the setp() Command

The setp() command is a specific utility function found in Python's matplotlib for setting multiple properties on a list of graphical "artists" (like lines or axes) using a MATLAB-style string/value pair format.

Example: Since ggplot2 is built on a declarative, layering system, there is no direct R equivalent of the setp() command. can use a combination of par() and with() to modify multiple properties at once.

setp() Goalggplot2 R ImplementationPurpose
Bulk Setting for Non-Data Itemstheme() functionUsed to apply consistent styling (e.g., font size, color, line width) to all axes, titles, or backgrounds simultaneously.
Bulk Setting for Data Items (Groups)scale_*_manual() functionsUsed to assign explicit colors, shapes, or line types to all levels of a mapped data variable.


Example in R

(Bulk Setting Axis Text using theme()): To set the color and size of all axis labels and tick marks globally:

p <- p + theme(axis.text = element_text(color = "grey50", size = 10),

               axis.line = element_line(linewidth = 0.5))

Example:

# Set multiple properties using par()

par(col = "orange", lwd = 3, pch = 18)

plot(x, y, type = "o", main = "Multiple Properties with par()")

5. Creating Multiple Plots

Creating multiple plots involves arranging individual ggplot2 objects into a single composite figure, essential for complex analysis where several views of the data are needed simultaneously.

Concept: Graph composition relies on specialized R packages that treat each individual ggplot2 object as a component to be positioned within a unified grid layout.

A. Modern R Implementation: patchwork and cowplot

Modern R data visualization favors extension packages like patchwork (known for its intuitive, simple syntax) or cowplot.


B. The cowplot::plot_grid() Function
The cowplot package provides the plot_grid() function, which allows explicit control over the layout, labels, and relative sizing of subplots.


Function / ArgumentPurposeExample
plot_grid(p1, p2,...)Basic function to combine individual plot objects (p1, p2) into a single grid.plot_grid(p_sales, p_profit)
nrow or ncolSpecifies the arrangement (rows or columns) for the combined figure.plot_grid(p1, p2, p3, nrow = 3) (Stacks plots vertically)
labelsAdds external, non-data labels (A, B, C...) to each subplot for reference.plot_grid(p1, p2, labels = c("A", "B"))
rel_widthsControls the relative width of columns in the layout.plot_grid(p1, p2, rel_widths = c(2, 1)) (p1 column is twice as wide as p2)


Example (Using cowplot to Combine Figures):


library(cowplot)


# p_rev and p_cust are two separate ggplot2 objects

p_rev <- ggplot(data_A, aes(x = Date, y = Revenue)) + geom_line() + labs(title = "Monthly Revenue")

p_cust <- ggplot(data_B, aes(x = Channel, y = Count)) + geom_bar(stat = "identity") + labs(title = "Customer Acquisition")


# Combine the plots side-by-side (ncol=2), label them, and adjust their width ratio

final_figure <- plot_grid(p_rev, p_cust,

                    ncol = 2,

                    labels = c("A. Revenue Trend", "B. Acquisition Channels"),

        rel_widths = c(1.5, 1)) # Give p_rev 1.5 times the width of p_cust

Example-

Multiple Lines in One Plot:

y1 <- c(1, 4, 9, 16, 25)

y2 <- c(1, 8, 27, 64, 125)

# Plot the first line

plot(x, y1, type = "o", col = "blue", ylim = c(0, 130),

     main = "Multiple Lines in One Plot", xlab = "X-axis", ylab = "Y-axis")

 # Add the second line

lines(x, y2, type = "o", col = "red")

legend("topleft", legend = c("y1 = x^2", "y2 = x^3"), col = c("blue", "red"), lty = 1, pch = 16)


Using par(mfrow) for Subplots:

The par() function can be used to create subplots within a single figure.

# Create a 1x2 layout

par(mfrow = c(1, 2))

 # First plot

plot(x, y1, type = "o", col = "blue", main = "Square Plot", xlab = "X", ylab = "Y")

 # Second plot

plot(x, y2, type = "o", col = "green", main = "Cube Plot", xlab = "X", ylab = "Y")

 # Reset layout

par(mfrow = c(1, 1))

Using layout() for Complex Subplots:

For more control over layout:

layout(matrix(c(1, 2, 3, 3), nrow = 2, byrow = TRUE))

 # Top left plot

plot(x, y1, type = "o", col = "red", main = "Top Left")

 # Top right plot

plot(x, y2, type = "o", col = "blue", main = "Top Right")

 # Bottom plot

plot(x, y1 + y2, type = "o", col = "purple", main = "Bottom")


The most used charts in data visualization:

  • Scatter Plot
  • Histogram
  • Bar & Stack Bar Chart
  • Box Plot
  • Area Chart
  • Heat Map
  • Correlogram

1. Scatter Plot

To see the relationship between two continuous variables.


2. Histogram

A histogram is used to plot a continuous variable. Also, It helps to break the data into bins and shows the frequency distribution of these bins. Thus, one can always change the bin size and see the effect it has on visualization.


3. Bar Chart

One can use bar charts to plot a categorical variable.


4. Box Plot

Box plots are used to plot an aggregation of categorical and continuous variables. It is also used for visualizing the spread of the data and detect outliers. Moreover, it shows five statistically significant numbers:

  • Minimum
  • 25th percentile
  • Median
  • 75th percentile and
  • Maximum.

5. Area Chart

One can use it to show the continuity across a variable or data set. It is almost same as a line chart. Also, we can use it for time series plots. We can use it alternatively to plot continuous variables and analyze the underlying trends.


6. Heat Map

One can use it for the intensity of colours. It is also used to display a relationship between two or three or many variables in a two-dimensional image. Thus, it allows us to explore two dimensions of the axis and the third dimension by an intensity of colour.



7. Correlogram

One can use it to test the level of correlation and also among the variable available in the dataset. Thus, the cells of the matrix can be shaded or coloured to show the co-relation value.








Comments

Popular posts from this blog

UNIT-1

Unit-5

Unit-2