Coordinate systems in ggplot2
Last Updated :
28 Apr, 2025
In R programming, ggplot2 is a well-liked library for data visualization. It offers a versatile method for producing a wide range of plots, including scatterplots, line plots, bar charts, histograms, and many more. Users of ggplot2 can produce visualizations that more clearly convey the patterns and relationships in their data by utilizing several coordinate systems.
Coordinate System in ggplot2
To depict the values of the data, the ggplot2 package uses two primary coordinate systems. They are:
- Linear Coordinate system
- Non-Linear Coordinate system
Linear Coordinate System in ggplot2
The Linear coordinate system is the one that mostly uses the cartesian coordinate system and is the default coordinate system of the ggplot2. It consists of the origin, which is where the two axis, i.e., the x and y axis intersect. This system is mainly used for zooming, fixing coordinates, and flipping coordinates. There are three types of linear coordinate systems. They are as follows:
Zooming the plot using coord_cartesian()
The coord_cartesian() is used to zoom in and out on a figure using the ggplot2 without affecting the underlying data. When dealing with data that has extreme numbers or outliers that obscure the subtleties of the remaining data, this can be helpful. The "xlim" and "ylim" parameters of the "coord_cartesian()" function specify the x and y-axis boundaries, respectively.
Syntax:
coord_cartesian(xlim = NULL, ylim = NULL, expand = TRUE)
Parameters:
- xlim: It is used to provide the x-axis limits. It accepts a vector of two values that represent the minimum and maximum x-axis limits. The boundaries remain unchanged if NULL.
- ylim: It accepts a vector of two values that define the minimum and maximum y-axis limits. The boundaries remain unchanged if NULL.
- expand: The axis limits can be slightly enlarged to make sure that all data points are visible by using this option. The axis bounds are increased if TRUE (the default), and collapsed if FALSE.
Now, let us see how to zoom in on a particular area of a barplot using coord_cartesian()
Example: Original graph
R
# load ggplot2
library(ggplot2)
# Create sample data
data <- data.frame(
Language = c("Python", "Java", "C++", "R", "Php"),
Popularity = c(14, 25, 23, 30, 10)
)
# Create a basic bar chart
ggplot(data, aes(x = Language, y = Popularity)) +
geom_bar(stat = "identity") +
labs(title = "Programming Language Popularity") +
xlab("Language") +
ylab("Popularity")
Output:
Original GraphExample: Graph after applying coord_cartesian()
R
# load ggplot2
library(ggplot2)
# Sample data
data <- data.frame( Language = c("Python", "Java", "C++", "C#", "JavaScript"),
Popularity = c(14, 25, 23, 18, 10))
# Create a bar chart using ggplot
ggplot(data, aes(x = Language, y = Popularity)) +
geom_bar(stat = "identity", fill = "steelblue") +
labs(title = "Programming Language Popularity",
x = "Language", y = "Popularity") +
# Set the y-axis limits to zoom in on y axis
coord_cartesian(ylim = c(0, 15))
Output:
In this example, we enlarged the area of the plot using coord_cartesian(). This produced a map that only displays the bars that fall within that range, which makes it simpler to see the specifics of the data in that region.
Zoomed in coordinates with coord_cartesian()Fixing Aspect Ratio with coord_fixed()
The fixed aspect ratio for the plot can be specified using the coord_fixed() function in ggplot2. When working with data where the relationship between the x and y variables is significant and should be maintained, this can be helpful. One argument, ratio, is required by the coord_fixed() method, and it determines the plot's aspect ratio as the relationship between its y and x units. The x and y scales are modified to have the same range of data units per inch when the plot's fixed aspect ratio is specified using the coord_fixed() function.
Syntax:
coord_fixed(ratio = 1, xlim = NULL, ylim = NULL)
Parameters:
- ratio: It is used to describe the plot's aspect ratio, which is the ratio of the plot's height to width. The plot has a square aspect ratio when the default value of 1 is used.
- xlim, ylim: It specifies the x-axis and y-axis boundaries. The boundaries are not altered if NULL.
Let us see how to set a fixed aspect ratio on a scatterplot using coord_fixed():
Example: Original graph
R
# load ggplot2
library(ggplot2)
# Create sample data
data <- data.frame(
theta = seq(0, 2 * pi, length.out = 50),
radius = rnorm(50)
)
# Create a basic scatterplot with polar coordinate
ggplot(data, aes(x = theta, y = radius)) +
geom_point() +
labs(title = "Scatterplot with Polar Coordinates System")
Output:
Original GraphExample: Graph after applying coord_fixed()
R
# load ggplot2
library(ggplot2)
# Sample data
data <- data.frame(x = c(10, 20, 30, 40, 50),
y = c(30, 60, 90, 120, 150))
# Create a scatterplot using ggplot
ggplot(data, aes(x = x, y = y)) +
geom_point() +
labs(title = "With Fixed Aspect Ratio- SCATTERPLOT",
x = "X-axis", y = "Y-axis") +
# Set the aspect ratio to 1:1
coord_fixed(ratio = 1)
Output:
In this example, a scatterplot was made. The plot was then given a fixed aspect ratio of 1:1 using coord_fixed(). This makes sure that the plot's aspect ratio doesn't change the relationship between the x and y variables.
Fixed Aspect Ratio with coord_fixed()Swapping Axes with coord_flip()
A graph's x and y axes can be flipped using the coord_flip() function in ggplot2. When working with data where the y variable should be shown horizontally and the x variable vertically, this can be helpful. Coord_flip() does not accept any arguments. The x and y axes of the plot are switched using the coord_flip() method, making the horizontal axis the vertical axis and vice versa.
Syntax:
coord_flip()
There are no parameters for the coord_flip() function.
Now, let us see the use of coord_flip() to change a bar chart's axes.
Example: Original graph
R
# load ggplot2
library(ggplot2)
# Create sample data
data <- data.frame(
x = c("P", "Q", "R", "S"),
y = c(100, 80, 60, 40)
)
# Create a basic bar chart
ggplot(data, aes(x = x, y = y)) +
geom_bar(stat = "identity") +
labs(title = "Bar Chart with Cartesian Coordinate System") +
xlab("Category") +
ylab("Value")
Output:
Original GraphExample: Graph after using coord_flip()
R
# load ggplot2
library(ggplot2)
# Create sample data
data <- data.frame(
x = c("P", "Q", "R", "S"),
y = c(100, 80, 60, 40)
)
# Create a basic bar chart
ggplot(data, aes(x = x, y = y)) +
geom_bar(stat = "identity") +
labs(title = "Bar Chart with Cartesian Coordinate System-coord_flip") +
xlab("Category") +
ylab("Value") +
# flipping axes
coord_flip()
Output:
In this example, we used a dataset of four categories and their values to build a bar chart. After switching the plot's x and y axes using coord_flip(), the bar chart was transformed into a horizontal bar chart.
Flipped axis with coord_flip()Non-Linear Coordinate System
The non-linear coordinate system is used for map projection, polar coordinates, and applying an arbitrary transformation to the axes. There are three types of non-linear coordinate systems. They are as follows:
Transforming Scales with coord_trans()
When there is a non-linear relationship between the data, one input, ytrans or xtrans, is required by the coord_trans() method to specify the transformation to be applied to the y or x-axis, respectively. The scales of the plot are transformed using the coord_trans() function, and as a result, the grid lines and tick labels are modified to reflect the translation.
Syntax:
coord_trans(x = NULL, y = NULL, xlim = NULL, ylim = NULL,
lambda = NULL, breaks = NULL, labels = NULL, trans = NULL)
Parameters:
- x/y: It specifies the transformation for the x-axis and y-axis, respectively. They accept either a function object representing a custom transformation or a character string indicating the transformation function, such as "log10" for a logarithmic transformation.
- xlim/ylim: It specifies the x-axis and y-axis boundaries. The boundaries remain unchanged if NULL.
- lambda: The Box-Cox transformation, a family of power transformations that includes the logarithmic transformation as a specific case, has lambda as its parameter. When the default value is NULL, no Box-Cox transformation is carried out.
- breaks and labels: To set the tick locations and labels for the converted axis, breaks and labels are used. They use the scale_*_continuous() functions' format as their starting point.
- trans: It is used to define a special transformation function that transforms a vector of values.
Let us see how to modify a line chart's y-axis with coord_trans()
Example: Original graph
R
# load ggplot2
library(ggplot2)
# Create sample data
data <- data.frame(
year = rep(c(2021, 2022, 2023), each = 4),
month = rep(c("May", "June", "July", "August"), times = 3),
value = rnorm(12)
)
# Create a basic line chart with faceted coordinate system
ggplot(data, aes(x = month, y = value, group = year)) +
geom_line() +
labs(title = "Line Chart with Faceted Coordinate System") +
xlab("Month") +
ylab("Value") +
facet_wrap(~ year, nrow = 1)
Output:
Original GraphExample: Graph after using coord_trans()
R
# load ggplot2
library(ggplot2)
# Create sample data
data <- data.frame(
year = rep(c(2021, 2022, 2023), each = 4),
month = rep(c("MAY", "JUNE", "JULY", "AUGUST"), times = 3),
value = rnorm(12, mean = 50000, sd = 10000)
)
# Create a basic line chart with faceted coordinate system
ggplot(data, aes(x = month, y = value, group = year)) +
geom_line() +
labs(title = "Line Chart with Faceted Coordinate System") +
xlab("Mon") +
ylab("Val") +
facet_wrap(~ year, nrow = 1) +
coord_trans(y = "log10")
Output:
In this example. we can see how the y-axis is altered using a logarithmic scale using the coord_trans() method. Using the data.frame() method, we first built a dataset with three years' worth of arbitrary data. Next, using the ggplot() function, we constructed a ggplot object with the dataset and aesthetic mappings.
Then, we used the geom_line() function to add a layer for the line chart and the coord_trans() function to change the y-axis to have a logarithmic scale. We can change the coordinate system scales by using the coord_trans() function, which accepts the scale transformation as an argument. In this instance, the y-axis scale was converted to a logarithmic scale using the formula y = "log10".
Transform scale with coord_transf()Polar Coordinated with coord_polar()
The ggplot2 package is used to create a scatterplot with a polar coordinate system. This type of coordinates is used to produce circular plots, including pie charts and radial plots. The data are plotted using the theta and radius radial axes.
Syntax:
coord_polar(theta = "x")
Parameter:
- theta: It specifies the angle (theta) determined by the x variable for polar coordinates.
Example:
R
# Load the ggplot2 package
library(ggplot2)
# Create a dataset
data <- data.frame(
theta = c(300, 600, 900, 1200, 1500, 1800),
radius = c(100, 200, 300, 400, 500, 600),
group = c("P", "Q", "R", "P", "Q", "R")
)
# Create a ggplot object with the dataset and aesthetic mappings
p <- ggplot(data, aes(x = theta, y = radius, color = group))
# Add a layer for the scatterplot
p <- p + geom_point()
# Specify the Polar coordinate system
p <- p + coord_polar()
# Display the plot
print(p)
Output:
This example showed how to make a scatterplot with a polar coordinate system using ggplot2's "coord_polar()" function. In order to produce the scatterplot with a polar coordinate system, the algorithm first created a dataset with three columns: one for the angle, one for the radius, and one for the group.
Polar coordinates with coord_polar()These examples all demonstrate how to use ggplot2 to produce visualizations with various coordinate systems, which can be useful for showcasing patterns or correlations in the data.
Similar Reads
Data visualization with R and ggplot2 The ggplot2 ( Grammar of Graphics ) is a free, open-source visualization package widely used in R Programming Language. It includes several layers on which it is governed. The layers are as follows:Layers with the grammar of graphicsData: The element is the data set itself.Aesthetics: The data is to
7 min read
Introduction to ggplot2
Working with External Data
Basic Plotting with ggplot2
Plot Only One Variable in ggplot2 Plot in RIn this article, we will be looking at the two different methods to plot only one variable in the ggplot2 plot in the R programming language. Draw ggplot2 Plot Based On Only One Variable Using ggplot & nrow Functions In this approach to drawing a ggplot2 plot based on the only one variable, firs
5 min read
How to create a plot using ggplot2 with Multiple Lines in R ?In this article, we will discuss how to create a plot using ggplot2 with multiple lines in the R programming language. Method 1: Using geom_line() function In this approach to create a ggplot with multiple lines, the user need to first install and import the ggplot2 package in the R console and then
3 min read
Plot Lines from a List of DataFrames using ggplot2 in RFor data visualization, the ggplot2 package is frequently used because it allows us to create a wide range of plots. To effectively display trends or patterns, we can combine multiple data frames to create a combined plot.Syntax: ggplot(data = NULL, mapping = aes(), colour())Parameters:data - Defaul
3 min read
How to plot a subset of a dataframe using ggplot2 in R ?In this article, we will discuss plotting a subset of a data frame using ggplot2 in the R programming language. Dataframe in use: Â AgeScoreEnrollNo117700521880103177915419752051885256199630717903581971409188345 To get a complete picture, let us first draw a complete data frame. Example: R # Load ggp
9 min read
Change Theme Color in ggplot2 Plot in RA theme in ggplot2 is a collection of settings that control the non-data elements of the plot. These settings include things like background colors, grid lines, axis labels, and text sizes. we can use various theme-related functions to customize the appearance of your plots, including changing theme
4 min read
Modify axis, legend, and plot labels using ggplot2 in RIn this article, we are going to see how to modify the axis labels, legend, and plot labels using ggplot2 bar plot in R programming language. For creating a simple bar plot we will use the function geom_bar( ). Syntax: geom_bar(stat, fill, color, width) Parameters :Â Â stat : Set the stat parameter to
5 min read
Common Geometric Objects (Geoms)
Advanced Data Visualization Techniques
Combine two ggplot2 plots from different DataFrame in RIn this article, we are going to learn how to Combine two ggplot2 plots from different DataFrame in R Programming Language. Here in this article we are using a scatter plot, but it can be applied to any other plot. Let us first individually draw two ggplot2 Scatter Plots by different DataFrames then
2 min read
Annotating text on individual facet in ggplot2 in RIn this article, we will discuss how to annotate a text on the Individual facet in ggplot2 in R Programming Language. To plot facet in R programming language, we use the facet_grid() function from the ggplot2 library. The facet_grid() is used to form a matrix of panels defined by row and column face
5 min read
How to annotate a plot in ggplot2 in R ?In this article, we will discuss how to annotate functions in R Programming Language in ggplot2 and also read the use cases of annotate. What is annotate?An annotate function in R can help the readability of a plot. It allows adding text to a plot or highlighting a specific portion of the curve. Th
4 min read
Annotate Text Outside of ggplot2 Plot in RGgplot2 is based on the grammar of graphics, the idea that you can build every graph from the same few components: a data set, a set of geomsâvisual marks that represent data points, and a coordinate system. There are many scenarios where we need to annotate outside the plot area or specific area as
2 min read
How to put text on different lines to ggplot2 plot in R?ggplot2 is a plotting package in R programming language that is used to create complex plots from data specified in a data frame. It provides a more programmatic interface for specifying which variables to plot onto the graphical device, how they are displayed, and general visual properties. In thi
3 min read
How to Connect Paired Points with Lines in Scatterplot in ggplot2 in R?In this article, we will discuss how to connect paired points in scatter plot in ggplot2 in R Programming Language. Scatter plots help us to visualize the change in two more categorical clusters of data. Sometimes, we need to work with paired quantitative variables and try to visualize their relatio
2 min read
How to highlight text inside a plot created by ggplot2 using a box in R?In this article, we will discuss how to highlight text inside a plot created by ggplot2 using a box in R programming language. There are many ways to do this, but we will be focusing on one of the ways. We will be using the geom_label function present in the ggplot2 package in R. This function allo
3 min read
Adding labels, titles, and legends in r
Working with Legends in R using ggplot2A legend in a plot helps us to understand which groups belong to each bar, line, or box based on its type, color, etc. We can add a legend box in R using the legend() function. These work as guides. The keys can be determined by scale breaks. In this article, we will be working with legends and asso
6 min read
How to Add Labels Directly in ggplot2 in RLabels are textual entities that have information about the data point they are attached to which helps in determining the context of those data points. In this article, we will discuss how to directly add labels to ggplot2 in R programming language. To put labels directly in the ggplot2 plot we add
5 min read
How to change legend title in ggplot2 in R?In this article, we will see how to change the legend title using ggplot2 in R Programming. We will use ScatterPlot. For the Data of Scatter Plot, we will pick some 20 random values for the X and Y axis both using rnorm() function which can generate random normal values, and here we have one more p
3 min read
How to change legend title in R using ggplot ?A legend helps understand what the different plots on the same graph indicate. They basically provide labels or names for useful data depicted by graphs. In this article, we will discuss how legend names can be changed in R Programming Language. Let us first see what legend title appears by default.
2 min read
Customizing Visual Appearance
Handling Data Subsets: Faceting
How to create a faceted line-graph using ggplot2 in R ?A potent visualization tool that enables us to investigate the relationship between two variables at various levels of a third-category variable is the faceted line graph. The ggplot2 tool in R offers a simple and versatile method for making faceted line graphs. This visual depiction improves our co
6 min read
How to Combine Multiple ggplot2 Plots in R?In this article, we will discuss how to combine multiple ggplot2 plots in the R programming language. Combining multiple ggplot2 plots using '+' sign to the final plot In this method to combine multiple plots, here the user can add different types of plots or plots with different data to a single p
2 min read
Change Labels of GGPLOT2 Facet Plot in RIn this article, we will see How To Change Labels of ggplot2 Facet Plot in R Programming language. To create a ggplot2 plot, we have to load ggplot2 package. library() function is used for that. Then either create or load dataframe. Create a regular plot with facets. The labels are added by default
3 min read
Change Font Size of ggplot2 Facet Grid Labels in RIn this article, we will see how to change font size of ggplot2 Facet Grid Labels in R Programming Language. Let us first draw a regular plot without any changes so that the difference is apparent. Example: R library("ggplot2") DF <- data.frame(X = rnorm(20), Y = rnorm(20), group = c("Label 1",
2 min read
Remove Labels from ggplot2 Facet Plot in RIn this article, we will discuss how to remove the labels from the facet plot in ggplot2 in the R Programming language. Facet plots, where one subsets the data based on a categorical variable and makes a series of similar plots with the same scale. We can easily plot a facetted plot using the facet_
2 min read
Grouping Data: Dodge and Position Adjustments