To produce a publication-quality data visualization, we often need to annotate the graph with various texts, symbols, or even shapes. In this recipe, we will learn how we can easily annotate an existing graph.
In this recipe, we will use the disA
and disD
variables from ggplotdata
. Let's call ggplotdata
for this recipe. We also need to call the grid
and gridExtra
libraries for this recipe.
In this recipe, we will execute the following annotation on an existing scatter plot. So, the whole procedure will be as follows:
Now, we will implement each of the steps one by one:
library(grid) library(gridExtra) # creating scatter plot and print it annotation_obj <- ggplot(data=ggplotdata,aes(x=disA,y=disD))+geom_point() annotation_obj # Adding custom text at (18,29) position annotation_obj1 <- annotation_obj + annotate(geom="text",x=18,y=29,label="Extreme value",size=3) annotation_obj1 # Highlight certain regions with a box annotation_obj2 <- annotation_obj1+ annotate("rect", xmin = 24, xmax = 27,ymin=17,ymax=22,alpha = .2) annotation_obj2 # Drawing line segment with arrow annotation_obj3 <- annotation_obj2+ annotate("segment",x = 16,xend=17.5,y=25,yend=27.5,colour="red", arrow = arrow(length = unit(0.5, "cm")),size=2) annotation_obj3
The preceding four steps are displayed in the following single graph:
The annotate()
function takes input of a geom
such as "segment"
and "text"
, and then it takes another input regarding position of that geom that is where to draw or where to place.. In this particular recipe, we used three geom
instances, such as text
to write customized text within the plot, rect
to highlight a certain region in the plot, and segment
to draw an arrow. The alpha
argument represents the transparency of the region and size
argument to represent the size of the text and line width of the line segment.
3.138.126.169