Is there a way to output a stem and leaf plot to a graphical device, such as window()
/ quartz()
? There are at least two ways to get stem and leaf plots in R: ?stem, in the graphics package, and ?stem.leaf, in the aplpack package. Both output text to the console. For example:
> set.seed(1)
> stem(rbinom(10, size=10, prob=.5))
The decimal point is at the |
3 | 0
4 | 000
5 | 0
6 | 00
7 | 000
It would be nice if this could be conveniently output to a graphical device where it could be combined with other plots (say a histogram) in a multi-figure layout, and/or saved as a png file. I am aware that you can output LaTeX and compile it into a pdf (e.g., see: Stem and Leaf from R into LaTeX), but this isn't very convenient and isn't really what I'm after. Is there an R function that can do this? Is there a simple hand-coded solution?
Instead, you can use a histogram or boxplot. To make a stem and leaf plot, split each data point into a stem and leaf value. The stem values divide the data points into groups. The stem value contains all the digits of a data point except the final number, which is the leaf.
The stems are on the left of the vertical line and the leaves are on the right. The stems are usually the first digit of a number. So if you have a value of 25, 2 is the stem that goes on the left of the vertical line and 5 is the leaf that goes on the right.
The 'stem' is on the left displays the first digit or digits. The 'leaf' is on the right and displays the last digit. For example, 543 and 548 can be displayed together on a stem and leaf as 54 | 3,8.
Stem and leaf plot uses numbers or data itself to show the data while the dot plot uses dots to represent the numbers. Therefore, they both give the same kind of information, which includes: The shape of the distribution that is how the data is distributed.
Here is one simple example:
plot.new()
tmp <- capture.output(stem(iris$Petal.Length))
text( 0,1, paste(tmp, collapse='\n'), adj=c(0,1), family='mono' )
If you want to overlay a histogram then you probably want to use the text
function on each of the elements of tmp
rather than paste
ing. Functions like strheight
and strwidth
will be useful to find the coordinates.
There are also functions in the gplots and plotrix packages for plotting text and adding tables to plots (other functions in other packages probably exist along these lines as well).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With