- R Graphs Cookbook Second Edition
- Jaynal Abedin Hrishi V. Mittal
- 327字
- 2021-08-05 17:30:34
Labeling data points
In this recipe, we will learn how to label individual or multiple data points with text.
Getting ready
For this recipe, we don't need to load any additional libraries. We just need to type the recipe in the R prompt or run it as a script.
How to do it...
Let's say we want to highlight one data point in the cars' scatter plot that we used in the previous few recipes. We can label it using the text()
command:
plot(mpg~disp, data=mtcars) text(258,22,"Hornet")

How it works...
In the preceding example, we first plotted the graph and then used the text()
function to overlay a label at a specific location. The text()
function takes the x and y coordinates and the text of the label as arguments. We specified the location as (258,22)
and the label text as Hornet
. This function is especially useful when we want to label outliers.
There's more...
We can also use the text()
function to label all the data points in a graph instead of just one or two. Let's look at another example where we wish to plot the life expectancy in countries versus their health expenditure. Instead of representing the data as points, let's use the name of countries to represent the values. We will use the HealthExpenditure.csv
example dataset:
health<-read.csv("HealthExpenditure.csv",header=TRUE) plot(health$Expenditure,health$Life_Expectancy,type="n") text(health$Expenditure,health$Life_Expectancy,health$Country)

We first use the plot()
command to create a graph of life expectancy versus expenditure. Note that we set type
equal to "n"
, which means that only the graph layout and axes are drawn but no data points are drawn. Then, we use the text()
function to place country names as labels at the x-y locations of all the data points. Thus, text()
accepts vectors as values for (x, y) and labels in order to dynamically label all the data points with the corresponding country names. If the text labels overlap, we can use the jitter()
function or remove some labels to reduce the overlap.
- Python GUI Programming:A Complete Reference Guide
- 深入淺出SSD:固態(tài)存儲(chǔ)核心技術(shù)、原理與實(shí)戰(zhàn)
- 硬件產(chǎn)品經(jīng)理手冊(cè):手把手構(gòu)建智能硬件產(chǎn)品
- Arduino BLINK Blueprints
- Building 3D Models with modo 701
- RISC-V處理器與片上系統(tǒng)設(shè)計(jì):基于FPGA與云平臺(tái)的實(shí)驗(yàn)教程
- 筆記本電腦芯片級(jí)維修從入門到精通(圖解版)
- USB應(yīng)用分析精粹:從設(shè)備硬件、固件到主機(jī)端程序設(shè)計(jì)
- Service Mesh微服務(wù)架構(gòu)設(shè)計(jì)
- 快·易·通:2天學(xué)會(huì)電腦組裝·系統(tǒng)安裝·日常維護(hù)與故障排除
- Applied Deep Learning with Keras
- Spring微服務(wù)實(shí)戰(zhàn)(第2版)
- 精選單片機(jī)設(shè)計(jì)與制作30例
- 51單片機(jī)新穎實(shí)例非常入門與視頻演練
- 數(shù)字噴墨與應(yīng)用