In R progamming I am using the plot function to generate a graph of data. I am struggling with figuring out if I am using the correct method for displaying a mean value onto the visualization.
I want to take a numeric dataset (column of a spreadsheet) and run a mean function on it and place that into a variable.
Example: mean_variable <- mean(table$numericcolumn
)
I then want to take that variable and print it into a label. Obviously the data is numeric, so I want to have a label to describe what this numeric value is.
Example: label("Average of Data:" mean_variable)
I have tried using several different labeling options.
My first thought since using the plot command and that the X axis is the data axis that the data for the mean, I would use the sub label. For display purposes lets say the value stored in the mean_variable is equal to 5. I tried the following for the sub title:
sub = "Average of Data:" toString(mean_variable)) sub = "Average of Data:" print(mean_variable))
I was expecting either of the above results to be "Average of Data: 5"
I am open to moving this outside of the subtitle if that makes more sense or is easier to manipulate. I am new to R so im not even sure if I am asking the right question. And as a result getting incorrect answers from searches as a result. I have been attempting to find information on how to display variables in labels.
There are a few ways to add text annotations to your plot. Nice tutorial on this here: https://www.statmethods.net/advgraphs/axes.html
First, you probably want to use paste()
to concatenate the label text with the number. It will coerce the numeric
into a character
for you.
You can use mtext()
to put annotations on the margin of the plot. There are arguments to control the position of this text.
You could use text()
to put the annotations directly into the plot area. There you need to supply the x
and y
position of the label and there are also arguments to nudge it if you want to put it next to a specific point rather than on top of.
mean_x <- mean(cars$speed)
mean_y <- mean(cars$dist)
plot(cars)
text(mean_x, mean_y, paste("Average of Data:", mean_x)) # goes in plot area
mtext(paste("Average of Data:", mean_x), side = 1) # goes on margin
Created on 2023-09-23 with reprex v2.0.2