Book Image

R Graph Essentials

Book Image

R Graph Essentials

Overview of this book

Table of Contents (11 chapters)
R Graph Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating histograms


In ggplot, we can create histograms using geom_histogram(). Histograms record frequencies for a continuous variable by dividing it into bins of a particular width. Using the medical dataset, use the following syntax to create a basic histogram of patient height, setting the bin width to 10 cm. Again, you can read the data by copying and pasting it from the code file for this chapter. The syntax is as follows:

ggplot(T, aes(x=HEIGHT)) + geom_histogram(binwidth=10)  

Within a histogram, we may wish to identify subgroups of the population using different colors. In our example, we can include a different color for each gender using a color scheme from scale_fill_brewer(). Again, we use a bin width of 10 cm:

ggplot(T, aes(x=HEIGHT, fill=GENDER)) + geom_histogram(binwidth=10) + scale_fill_brewer(type = "div", palette = 4) 

Here is what the histogram looks like:

Essentially, we have two histograms together. This information is very useful, but perhaps a better alternative...