Course
15 Questions All R Users Have About Plots
R allows you to create different plot types, ranging from the basic graph types like density plots, dot plots, boxplots and scatter plots, to the more statistically complex types of graphs such as probability plots.
In addition, it allows you to go from producing basic graphs with little customization to plotting advanced graphs with full-blown customization in combination with interactive graphics. Nevertheless, not always do we get the results that we want for our R plots: Stack Overflow is flooded with our questions on plots, with many recurring questions.
This is why DataCamp decided to put all the frequently asked questions and their top rated answers together in a blog post.
To practice creating plots in R, try this course on data visualization in R.
The 15 R Plots Questions
1. How to Draw an Empty R Plot
Open a New Plot Frame
You can open an empty plot frame and activate the graphics device in R as follows:Note that the plot.new()
and frame()
functions define a new plot frame without it having any axes, labels, or outlining. It indicates that a new plot is to be made: a new graphics window will open if you don’t have one open yet, otherwise the existing window is prepared to hold the new plot. You can read up on these functions here.
Set up the Measurements of the Graphics Window
You can also use the plot.window()
function to set the horizontal and vertical dimensions of the empty plot you just made:
plot.new()
pWidth = 3
pHeight = 2
plot.window(c(0,pWidth),
c(0,pHeight))
Draw an Actual Empty Plot
You can draw an empty plot with the plot()
function. Additionally, fill up the empty plot with axes, axes labels and a title with the mtext()
and title()
functions.
You give the coordinates (5,5) for the plot, but that you don’t show any plotting by putting the type
argument to "n"
.
Tip: try to put this argument to "p"
or "b"
and see what happens!
What’s more, you don’t annotate the plot, but you do put limits from 0
to 10
on the x- and y-axis.
Lastly, you may choose to draw a box around your plot by using the box()
function and add some points to it with the points()
function:
Note that you can put your x-coordinates and y-coordinates in vectors to plot multiple points at once. The pch
argument allows you to select a symbol, while the cex
argument has a value assigned to it that indicates how much the plotted text and symbols should be scaled with respect to the default.
Tip: if you want to see what number links to what symbol, click here.
2. How to Set the Axis Labels and Title of the R Plots
The axes of the R plots make up one of the most popular topics of Stack Overflow questions; The questions related to this topic are very diverse.
Keep on reading to find out what type of questions DataCamp has found to be quite common!
Name Axes (With Up- Or Subscripts) and Put a Title to an R Plot?
You can easily name the axes and put a title in place to make your R plot more specific and understandable for your audience.
This can be easily done by adding the arguments main
for the main title, sub
for the subtitle, xlab
for the label of the x-axis and ylab
for the label of the y-axis.
Note that if you want to have a title with up-or subscripts, you can easily add these in the main
argument of the plot()
function. Make sure to use an expression()
and use the ^
symbol for upscripts or square brackets for a subscript.
Try it out in the DataCamp Light chunk below:
You can also make sure that you have Greek letters in your axis labels by using code which combines the expression()
and paste()
functions. Execute the following piece of code:
Adjust the Appearance of the Axes’ Labels
To adjust the appearance of the x-and y-axis labels, you can use the argumentscol.lab
and cex.lab
. The first argument is used to change the color of the x-and y-axis labels, while the second argument is used to determine the size of the x-and y-axis labels, relative to the (default) setting of cex
.
For more information on these arguments, go to this page.
Remove a Plot’s Axis Labels and Annotations
If you want to get rid of the axis values of a plot, you can first add the arguments xaxt
and yaxt
, set as "n"
. These arguments are assigned a character which specifies the x-axis type. If you put in an "n"
, like in the command below, you can suppress the plotting of the axis.
Note that by giving any other character to the xaxt
and yaxt
arguments, the x-and y-axes are plotted.
ann
and set it to FALSE
to make sure that any axis labels are removed.
Tip: not the information you are looking for? Go to this page.
Rotate a Plot’s Axis Labels
You can add thelas
argument to the axis()
function to rotate the numbers that correspond to each axis:
Note how this actually requires you to add an argument to the plot()
function that basically says that there are no axes to be plotted (yet): this is the task of the two axis()
function that come next.
The las
argument can have three values attributed to it. According to whichever option you choose, the placement of the label will differ: if you choose 0
, the label will always be parallel to the axis (which is the default); If you choose 1
, the label will be put horizontally. Pick 2
if you want it to be perpendicular to the axis and 3
if you want it to be placed vertically.
But there is more. If you want to know more about the possibilities of the axis()
function, keep on reading!
Move the Axis Labels of your R Plot
So, you want to move your axes’ labels around?
No worries, you can do this with the axis()
function; As you may have noticed before in this tutorial, this function allows you to first specify where you want to draw the axes. Let’s say you want to draw the x-axis above the plot area and the y-axis to the right of it.
Remember that if you pass 1
or 2
to the axis()
function, your axis will be drawn on the bottom and on the left of the plot area. Scroll a bit up to see an example of this in the previous piece of code!
3
and 4
to the axis()
function:
As you can see, at first, you basically plot x
and y
, but you leave out the axes and annotations. Then, you add the axes that you want to see and specify their location with respect to the plot.
The flexibility that the axis()
function creates for you keeps on growing! Check out the next frequently asked question to see what else you can solve by using this basic R function.
Tip: go to the last question to see more on how to move around text in the axis labels with hjust
and vjust
!
3. How to Add and Change the Spacing of the Tick Marks of your R Plot
How to Change the Spacing of the Tick Marks of your R Plot
Letting R determine the tick marks of your plot can be quite annoying and there might come a time when you will want to adjust these.
1. Using the axis()
Function to Determine the Tick Marks of your Plot
As you can see, you first define the position of the tick marks and their labels. Then, you draw your plot, specifying the x axis type as "n"
, suppressing the plotting of the axis.
Then, the real work starts:
- The
axis()
function allows you to specify the side of the plot on which the axis is to be drawn. In this case, the argument is completed with1
, which means that the axis is to be drawn below. If the value was2
, the axis would be drawn on the left and if the value was3
or4
, the axis would be drawn above or to the right, respectively; - The
at
argument allows you to indicate the points at which tick marks are to be drawn. In this case, you use the positions that were defined inV1
; - Likewise, the
labels
that you want to use are the ones that were specified inV2
; - You adjust the direction of the ticks through
tck
: by giving this argument a negative value, you specify that the ticks should appear below the axis.
Tip: try passing a positive value to the tck
argument and see what happens!
tcl
and the appearance of the tick labels is controlled with cex.axis
, col.axis
and font.axis
.
2. Using other Functions to Determine the Tick Marks of your R Plot
You can also use the par()
and plot()
functions to define the positions of tickmarks and the number of intervals between them.
xaxp
to which you pass the position of the tick marks that are located at the extremes of the x-axis, followed by the number of intervals between the tick marks:
You can also run the following code to basically get the same result:
Note that this works only if you use no logarithmic scale. If the log coordinates set as true, or, in other words, if par(xlog=T)
, the three values that you pass to xaxp
have a different meaning: for a small range, n
is negative. Otherwise, n
is in 1:3, specifying a case number, and x1 and x2 are the lowest and highest power of 10 inside the user coordinates, 10 ^ par(“usr”)[1:2].
In this example, you use the par()
function: you set xlog
to TRUE
and add the xaxp
argument to give the coordinates of the extreme tick marks and the number of intervals between them. In this case, you set the minimum value to 1
, the maximal value to 4
and you add that the number of intervals between each tick mark should be 3
.
Then, you plot x
and y
, adding the log
argument to specify whether to plot the x-or y-axis or both on a log scale. You can pass "x"
, "y"
, and "xy"
as values to the log arguments to do this.
How to add Minor Tick Marks to an R Plot
You can quickly add minor tick marks to your plot with theminor.tick()
function from the Hmisc
package:
- The
nx
argument allows you to specify the number of intervals in which you want to divide the area between the major tick marks on the axis. If you pass the value1
to it, the minor tick marks will be suppressed; ny
allows you to do the same asnx
, but then for the y-axis;- The
tick.ratio
indicates the ratio of lengths of minor tick marks to major tick marks. The length of the latter is retrieved frompar(tck=x)
.
4. How to Create Two Different X- or Y-axes
The first option is to create a first plot and to execute thepar()
function with the new
argument put to TRUE
to prevent R from clearing the graphics device:
Then, you create the second plot with plot()
. Pass in the data, and then also make sure that you adjust some of the arguments, such as type
, axes
, bty
, xlab
and ylab
:
type
: you can pass inl
to make sure that you plot with lines;axes
is set toFALSE
so that no axes are plotted;bty
suppresses the drawing of the box around the plot;xlab
is set to an empty string, which makes that there is no label on the x-axis, andylab
is also set to an empty string, so the y-axis also has no label.
Check it all out in the following DataCamp Light chunk. Note that the code from above has already been loaded in into your working environment. You can double check by using the R Console on the right-hand side of the DataCamp Light box:
Next, it’s time to add an axis and to write text into the margins of the plot with axis()
and mtext()
respectively.
You can add a new axis on the right-hand side by adding the argument side
and assigning it the value 4
to the axis()
function. Next, you specify the at
argument to indicate the points at which tick-marks need to be drawn. In this case, you compute a sequence of n+1 equally spaced “round” values which cover the range of the values in z
with the pretty()
function. This ensures that you actually have the numbers from the y-axis from your second plot, which you named z
.
Try all of this out below:
Note that the side
argument can have three values assigned to it: 1
to place the text to the bottom, 2
for a left placement, 3
for a top placement and 4
to put the text to the right. The line
argument indicates on which margin line the text starts.
The total end result of your code will look like this:
set.seed(101)
x <- 1:10
y <- rnorm(10)
z <- runif(10, min=1000, max=10000)
plot(x, y)
par(new = TRUE)
plot(x,
z,
type = "l",
axes = FALSE,
bty = "n",
xlab = "",
ylab = "")
axis(side=4,
at = pretty(range(z)))
mtext("z",
side=4,
line=3)
As an additional exercise, try constructing an R plot with two different x-axes! Do this in this DataCamp Light chunk below:
Note that, even though you can do all this manually with the basic plot()
, axis()
and mtext()
functions, there are packages that automate all of this: the twoord.plot()
function of the plotrix
package and doubleYScale()
function of the latticeExtra
package are quite handy and perhaps a bit faster if you want to do the same thing:
Note that the example above is made with this dataset. If you have any doubts about the importing of the data or the read.table()
function, check out DataCamp’s tutorial on importing data in R.
5. How to add or Change the R Plot’s Legend
Adding and Changing an R Plot’s Legend with Basic R
You can easily add a legend to your R plot with thelegend()
function:
Note that the arguments pt.cex
and title.cex
that are described in the documentation of legend()
don’t really work. There are some workarounds:
- Put the title or the labels of the legend in a different font by adding the
text.font
argument tolegend()
:
- Draw the legend twice with different
cex
argument values
Tip: if you’re interested in knowing more about the colors that you can use in R, check out this very helpful PDF document.
How to add and Change an R Plot’s Legend and Labels In ggplot2
Adding a legend to your ggplot2 plot is fairly easy. You can just execute the following:
And it gives you a default legend. But, in most cases, you will want to adjust the appearance of the legend some more.
There are two ways of changing the legend title and labels in ggplot2
:
- Tell the scale to use have a different title and labels
colour
or shape
, or other aesthetics, you need to change the names and labels through the scale_color_discrete()
and scale_shape_discrete()
functions, respectively:
Note that the plot looks a bit squished in the Plot tab of the DataCamp Light chunk, but that this wouldn’t be a problem if you execute the code in RStudio.
Note that you can create two legends if you add the argument shape
into the geom_point()
function and into the labels
arguments!
If you want to move the legend to the bottom of the plot, you can specify the legend.position
as "bottom"
. The legend.justification
argument, on the other hand, allows you to position the legend inside the plot.
Tip: check out all kinds of scales that could be used to let ggplot know that other names and labels should be used here.
- Change the data frame so that the factor has the desired form
You can then use the new factor names to make your plot in ggplot2, avoiding the “hassle” of changing the names and labels with extra lines of code in your plotting.
Tip: for a complete cheat sheet on ggplot2, you can go here.
6. How to Draw a Grid in your R Plot
Drawing a Grid in your R Plot with Basic R
For some purposes, you might find it necessary to include a grid in your plot. You can easily add a grid to your plot by using thegrid()
function:
Drawing a Grid in an R Plot with ggplot2
The code chunk below shows you how you can make sure that your plot has a grid with the ggplot2
package. Note that the chol
data has already been loaded in and that the data manipulation steps from above have been applied to it.
If you’re not sure what the data looks like, print out the first rows of the data frame in the R Console of the DataCamp Light chunk:
Tip: if you don’t want to have the minor grid lines, just pass element_blank()
to panel.grid.minor
.
If you want to fill the background up with a color, add the panel.background = element_rect(fill = "navy")
to your code. You can see how this is done in the DataCamp Light block below. The chol
data has been loaded and lightly manipulated, just like before. Try it out for yourself!
7. How to Draw a Plot with a PNG as Background
You can quickly draw a plot with a .png as a background with the help of the png
package. You install the package if you need to, activate it for use in your workspace through the library function library()
and you can start plotting!
First, you want to load in the image. Use the readPNG()
function to specify the path to the picture!
tip: you can check where your working directory is set at and change it by executing the following commands.
If your picture is saved in your working directory, you can just specify readPNG("picture.png")
instead of passing the whole path.
Next, you want to set up the plot area and you want to call the par()
function to set the graphical parameters in rasterImage()
. You use the argument usr
to define the extremes of the user coordinates of the plotting region. In this case, you put 1
, 3
, 2
and 4
.
Next, you draw a grid and add some lines:
install.packages("png")
library(png)
image <- readPNG("<path to your picture>")
getwd()
setwd("<path to a folder>")
plot(1:2, type='n', main="Plotting Over an Image", xlab="x", ylab="y")
lim <- par()
rasterImage(image, lim$usr[1], lim$usr[3], lim$usr[2], lim$usr[4])
grid()
lines(c(1, 1.2, 1.4, 1.6, 1.8, 2.0), c(1, 1.3, 1.7, 1.6, 1.7, 1.0), type="b", lwd=5, col="red")
This can give you the following result if you use the DataCamp logo:
library(png)
image <- readPNG("datacamp.png")
plot(1:2, type="n", main="Plotting Over an Image", xlab="x", ylab="y", asp=1)
lim <- par()
rasterImage(image, lim$usr[1], lim$usr[3], lim$usr[2], lim$usr[4])
lines(c(1, 1.2, 1.4, 1.6, 1.8, 2.0), c(1.5, 1.3, 1.7, 1.6, 1.7, 1.0), type="b", lwd=5, col="red")
Note that you need to give a .png file as input to readPNG()
and that, if you would like to, you can also follow the same procedure to work with jpg images. Of course, you then need to load in the jpeg
library!
Note that in this example, you first download an image from the web to use in your plot, but that you can also just save an image and pass the file path to readJPEG()
to make use of it during plotting.
Also, note that this example was taken from the R Graph Gallery, which offers a ton of inspiration for R data visualization, as you can find the code and the renderings in one space! It’s ideal if you’re looking for inspiration or a quick way to find the code you need for your graphs!
8. How to Adjust the Size of Points in an R Plot
Adjusting the Size of Points in an R Plot with Basic R
To adjust the size of the points with basic R, you might just simply use thecex
argument:
symbols()
:
The circles of this plot receive the values of df$x3
as the radii, while the argument inches
controls the size of the symbols. When this argument receives a positive number as input, the symbols are scaled to make largest dimension this size in inches.
Adjusting the Size of Points in your R Plot with ggplot2
In this case, you will want to adjust the size of the points in your scatterplot. You can do this with the size
argument. Note that the chol
data has been loaded in for you:
Note that you can also pass the size
argument to the geom_point()
function:
ggplot(chol,
aes(x=chol$WEIGHT, y=chol$HEIGHT)) +
geom_point(size = 2)
You’ll get the same result, but don’t take my word for it! Try replacing the last piece of code in the DataCamp Light chunk with this chunk.
9. How to Fit a Smooth Curve to your R Data
The loess()
function is probably every R programmer’s favorite solution for this kind of question. It actually “fits a polynomial surface determined by one or more numerical predictors, using local fitting”.
In short, you have your data and you use the loess()
function, in which you correlate y
and x
. Through this, you specify the numeric response and one to four numeric predictors.
x
and y
and you plot lines in the original plot where you predicted the values of lo
:
10. How to add Error Bars in an R Plot
Drawing Error Bars with Basic R
The bad news: R can’t draw error bars just like that. The good news: you can still draw the error bars without needing to install extra packages!
First, you’ll need to define the following function to calculate some summary statistics of your data frame:
summarySE <- function(data=NULL, measurevar, groupvars=NULL, na.rm=FALSE,
conf.interval=.95, .drop=TRUE) {
library(plyr)
# New version of length which can handle NA's: if na.rm==T, don't count them
length2 <- function (x, na.rm=FALSE) {
if (na.rm) sum(!is.na(x))
else length(x)
}
# This does the summary. For each group's data frame, return a vector with
# N, mean, and sd
datac <- ddply(data, groupvars, .drop=.drop,
.fun = function(xx, col) {
c(N = length2(xx[[col]], na.rm=na.rm),
mean = mean (xx[[col]], na.rm=na.rm),
sd = sd (xx[[col]], na.rm=na.rm)
)
},
measurevar
)
# Rename the "mean" column
datac <- rename(datac, c("mean" = measurevar))
datac$se <- datac$sd / sqrt(datac$N) # Calculate standard error of the mean
# Confidence interval multiplier for standard error
# Calculate t-statistic for confidence interval:
# e.g., if conf.interval is .95, use .975 (above/below), and use df=N-1
ciMult <- qt(conf.interval/2 + .5, datac$N-1)
datac$ci <- datac$se * ciMult
return(datac)
}
Note that the function definition comes from this source and that it is also available through the Rmisc
library.
Next, you can use this to calculate some statistics of the chol
data, which has already been loaded in for you. After, you can use these resulting numbers to make your plot.
Make sure to inspect the data before you start this exercise!
If you want to read up on all the arguments that arrows()
can take, go here.
Drawing Error Bars With ggplot2
Error Bars Representing Standard Error Of Mean
First summarize your data with the summarySE()
function from the Rmisc package or use the function that has been defined above. Then, you can use the resulting dataframe to plot some of the variables, drawing error bars for them at the same time, with, for example, the standard error of mean.
position_dodge()
function:
Tip: if you get an error like “geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?”, it usually requires you to adjust the group aesthetic.
Error Bars Representing Confidence Intervals
Continuing from the summary of your data that you made with the summarySE()
function of the Rmisc
library or of the previous section, you can also draw error bars that represent confidence intervals. In this case, a plot with error bars of 95% confidence are plotted.
Note how the color of the error bars is now set to black with the colour
argument.
Error Bars Representing The Standard Deviation
Lastly, you can also use the results of the summarySE()
function of the Rmisc
package or from the function definition that you have copied from one of the last sections to plot error bars that represent the standard deviation.
Specifically, you would just have to adjust the ymin
and ymax
arguments that you pass to geom_errorbar()
:
Big tip*: also take a look at this for more detailed examples on how to plot means and error bars.
11. How To Save A Plot As An Image On Disc
You can use dev.copy()
to copy your graph, made in the current graphics device to the device or folder specified by yourself.
x <- seq(0,2*pi,0.1)
y <- sin(x)
plot(x,y)
dev.copy(jpeg,
filename="<path to your file/name.jpg>");
dev.off();
(x)
(y)
12. How To Plot Two R Plots Next To Each Other
Plot Two Plots Side by Side Using Basic R
You can do this with basic R commands:By adding the par()
function with the mfrow
argument, you specify a vector, which in this case contains 1 and 2: all figures will then be drawn in a 1-by-2 array on the device by rows (mfrow
).
In other words, the boxplots from above will be printed in one row inside two columns.
Plot Two Plots Next to each other Using ggplot2
If you want to put plots side by side and if you don’t want to specify limits, you can consider using the ggplot2
package to draw your plots side-by-side.
Your data chol
and the summarySE()
function have been loaded in. Inspect them in the R Console if you’re not sure what they look like:
Note how you just add the facet_grid()
function to indicate that you want two plots next to each other. The element that is used to determine how the plots are drawn, is MORT
, as you can well see above!
Plot more Plots Side by Side Using gridExtra
To get plots printed side by side, you can use the gridExtra
package; Make sure you have the package installed and activated in your workspace and then execute something like this:
Note how here again you determine how the two plots will appear to you thanks to the ncol
argument.
Plot more Plots Side by Side Using lattice
Just like the solution with ggplot2
package, the lattice
package also doesn’t require you to specify limits or the way you want your plots printed next to each other.
Instead, you use bwplot()
to make trellis graphs with the graph type of a box plot. Trellis graphs display a variable or the relationship between variables, conditioned on one or more other variables.
In this case, if you’re using the chol
data set (which you can find here or load in with the read.table()
function, you display the variable CHOL
separately for every combination of factor SMOKE
and MORT
levels.
Note that the data has been loaded in for you in the DataCamp Light chunk below!
Plotting Plots Next to each other with gridBase
Another way even to put two plots next to each other is by using the gridBase
package, which takes care of the “integration of base and grid graphics”. This could be handy when you want to put a basic R plot and a ggplot next to each other.
You work as follows: first, you activate the necessary packages in your workspace. In this case, you want to have gridBase
ready to put the two plots next to each other and grid
and ggplot2
to actually make your plots:
library(grid)
library(gridBase)
library(ggplot2)
plot.new()
gl <- grid.layout(nrow=1,
ncol=2)
vp.1 <- viewport(layout.pos.col=1,
layout.pos.row=1)
vp.2 <- viewport(layout.pos.col=2,
layout.pos.row=1)
pushViewport(viewport(layout=gl))
pushViewport(vp.1)
par(new=TRUE,
fig=gridFIG())
plot(x = 1:10,
y = 10:1)
popViewport()
pushViewport(vp.2)
ggplotted <- qplot(x=1:10,y=10:1, 'point')
print(ggplotted, newpage = FALSE)
popViewport(1)
If you want and need it, you can start an empty plot to then set up the layout. Note that since you want the two plots to be generated next to each other, this requires you to make a grid layout consisting of one row and two columns.
Now, you want to fill up the cells of the grid with viewports. These define rectangular regions on your graphics device with the help of coordinates within those regions. In this case, it’s much more handy to use the specifications of the grid that have just been described above rather than real x-or y-coordinates. That is why you should use the layout.pos.col
and layout.pos.row
arguments.
Since the viewports are only descriptions or definitions, these kinds of objects need to be pushed onto the viewport tree before you can see any effect on the drawing. You want to use the pushViewport()
function to accomplish this.
Now you can proceed to adding the first rectangular region vp.1
to the ViewPort tree, after which you tell R with gridFig()
to draw a base plot within a grid viewport (vp.1
, that is). The fig
argument normally takes the coordinates of the figure region in the display region of the device. In this case, you use the fig
argument to start a new plot, adding it to an existing plot use by adding new = TRUE
in the par()
function as well. You plot the base graphic and remove the viewport from the tree:
plot.new()
gl <- grid.layout(nrow=1,
ncol=2)
vp.1 <- viewport(layout.pos.col=1,
layout.pos.row=1)
vp.2 <- viewport(layout.pos.col=2,
layout.pos.row=1)
pushViewport(viewport(layout=gl))
pushViewport(vp.1)
par(new=TRUE,
fig=gridFIG())
plot(x = 1:10,
y = 10:1)
popViewport()
Since you want the two plots to be generated next to each other, you want to put one plot in the first column and the other in the second column, both located on the first row.
Note that the pushViewport()
function takes the viewport()
function, which in itself contains a layout
argument. This last argument indicates “a grid layout object which splits the viewport into subregions”.
Note also that you can specify in the popViewport()
function an argument to indicate how many viewports you want to remove from the tree. If this value is 0, this indicates that you want to remove the viewports right up to the root viewport. The default value of this argument is 1.
Go to add the second rectangular region vp.2
to the ViewPort tree. You can then make the ggplot and remove the viewport from the tree.
pushViewport(vp.2)
ggplotted <- qplot(x=1:10,
y=10:1,
'point')
print(ggplotted,
newpage = FALSE)
popViewport(1)
Note that you need to print to print the graphics object made by qplot()
in order to actually draw it and get it displayed. At the same time, you also want to specify newpage = FALSE
, otherwise you’ll only see the qplot()
…
Also, remember that the default value of viewports to remove in the function popViewport()
is set at 1. This makes it kind of redundant to put popViewport(1)
in the code.
13. How to Plot Multiple Lines or Points
Using Basic R to Plot Multiple Lines or Points in the same R Plot
To plot two or more graphs in the same plot, you basically start by making a typical basic plot in R. Then, you start adding more lines or points to the plot. In this case, you add more lines to the plot, so you’ll define more y axes:Next, you see that these lines are plotted with the use of the lines()
function.
This gives the following result:
Note that the lines()
function takes in three arguments: the x-axis and the y-axis that you want to plot and the color (represented with the argument col
) in which you want to plot them. You can also include the following features:
Feature | Argument | Input |
---|---|---|
Line type | lty |
Integer or character string |
Line width | lwd |
Integer |
Plot type | pch |
Integer or single character |
Line end style | lend |
Integer or string |
Line join style | ljoin |
Integer or string |
Line mitre limit | lmitre |
Integer < 1 |
Here are some examples:
lines(x,y2,col="green", lty = 2, lwd = 3)
lines(x,y2,col="green", lty = 5, lwd = 2, pch = 2)
lines(x,y3,col="black", lty = 3, lwd = 5, pch = 3, lend = 0, ljoin = 2)
lines(x,y4,col="blue", lty = 1, lwd = 2, pch = 3, lend = 2, ljoin = 1, lmitre = 2)
Note that the pch
argument does not function all that well with the lines()
function and that it’s best to use it only with points()
.
points()
function:
You can add the same arguments to the points()
function as you did with the lines()
function and that are listed above. There are some additions, though:
Feature | Argument | Input |
---|---|---|
Background (fill) color | bg |
Only if pch = 21:25 |
Character (or symbol) expansion | cex |
Integer |
Code examples of these arguments are the following:
points(x,y4,col="blue", pch=21, bg = "red")
points(x, y5, col="yellow", pch = 5, bg = "blue")
If you incorporate these changes into the plot that you see above, you will get the following result:
Using ggplot2
to Plot Multiple Lines or Points In One R Plot
The ggplot2
package conveniently allows you also to create layers, which will enable you to basically plot two or more graphs into the same R plot without any difficulties and pretty easily:
14. How to Fix the Aspect Ratio for your R Plots
If you want to put your R plot to be saved as an image where the axes are proportional to their size, it’s a sign that you want to fix the aspect ratio.
Adjusting the Aspect Ratio with Basic R
When you’re working with basic R commands to produce your plots, you can add the argumentasp
of the plot()
function, completed with an integer, to set your aspect ratio. Look at this first example without a defined aspect ratio:
asp
:
Adjusting the Aspect Ratio for your Plots with ggplot2
To fix the aspect ratio for ggplot2 plots, you just add the function coord_fixed()
, which provides a “fixed scale coordinate system [that] forces a specified ratio between the physical representation of data units on the axes”.
In other words, this function allows you to specify a number of units on the y-axis which is equivalent to one unit on the x-axis. The default is always set at 1, which means that one unit on the x-axis has the same length as one unit on the y-axis. If your ratio is set at a higher value, the units on the y-axis are longer than units on the x-axis and vice versa.
Compare the following examples:Adjusting the Aspect Ratio for your Plots with MASS
You can also consider using the MASS package, which encompasses the eqscplot()
function: it produces plots with geometrically equal scales. It does this for scatterplots:
Tip: you might do well starting a new plot frame before executing the code above!
Note that you can give additional arguments to the eqscplot()
function to customize the scatterplot’s look!
15. What is the Function of hjust
and vjust
in ggplot2
Well, you basically use these arguments when you want to set the position of text in your ggplot. hjust
allows you to define the horizontal justification, while vjust
is meant to control the vertical justification. See the documentation on geom_text()
for more information.
To demonstrate what exactly happens, you can create a data frame from all combinations of factors with the expand.grid()
function:
hjustvjust <- expand.grid(hjust=c(0, 0.5, 1),
vjust=c(0, 0.5, 1),
angle=c(0, 45, 90),
text="Text"
)
Note that hjust
and vjust
can only take values between 0 and 1.
0
means that the text is left-justified; In other words, all text is aligned to the left margin. This is usually what you see when working with text editors such as Microsoft Word.1
means that the text is right-justified: all text is aligned to the right margin.
ggplot()
function, defining the x-and y-axis as hjust
and vjust
respectively:
Also note how the hjust
and vjust
arguments are added to geom_text()
, which takes care of the textual annotations to the plot.
In the plot above you see that the text at the point (0,0) is left-aligned, horizontally as well as vertically. On the other hand, the text at point (1,1) is right-aligned in horizontal as well as vertical direction. The point (0.5,0.5) is right in the middle: it’s not really left-aligned nor right-aligned for what concerns the horizontal and vertical directions.
Note that when these arguments are defined to change the axis text, the horizontal alignment for axis text is defined in relation to the entire plot, not to the x-axis!vjust
argument to change the axis text does to the representation of your plot:
To go to the excellent original discussion, from which the code above was adopted, click here.
As a Last Note…
It’s worth checking out this article, which lists 10 tips for making your R graphics look their best!
Also, if you want to know more about data visualization, you might consider checking out DataCamp’s interactive course on data visualization with ggvis, given by Garrett Grolemund, author of Hands on Programming with R, as well as Data Science with R.
Or maybe our course on reporting with R Markdown can interest you!
Learn more about R
Course
Introduction to the Tidyverse
Course
Intermediate Data Visualization with ggplot2
tutorial
Types of Data Plots and How to Create Them in Python
tutorial
Box Plot in R Tutorial
DataCamp Team
4 min
tutorial
Scatterplot in R
DataCamp Team
tutorial
The R Graph Gallery's Top 5 Most Visited Graph Themes
DataCamp Team
8 min
tutorial
How to Make a ggplot2 Histogram in R
Kevin Babitz
15 min
tutorial