Histograms and frequency polygons — geom_freqpoly (2024)

Visualise the distribution of a single continuous variable by dividingthe x axis into bins and counting the number of observations in each bin.Histograms (geom_histogram()) display the counts with bars; frequencypolygons (geom_freqpoly()) display the counts with lines. Frequencypolygons are more suitable when you want to compare the distributionacross the levels of a categorical variable.

Usage

geom_freqpoly( mapping = NULL, data = NULL, stat = "bin", position = "identity", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE)geom_histogram( mapping = NULL, data = NULL, stat = "bin", position = "stack", ..., binwidth = NULL, bins = NULL, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE)stat_bin( mapping = NULL, data = NULL, geom = "bar", position = "stack", ..., binwidth = NULL, bins = NULL, center = NULL, boundary = NULL, breaks = NULL, closed = c("right", "left"), pad = FALSE, na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE)

Arguments

mapping

Set of aesthetic mappings created by aes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supply mapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

If NULL, the default, the data is inherited from the plotdata as specified in the call to ggplot().

A data.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

A function will be called with a single argument,the plot data. The return value must be a data.frame, andwill be used as the layer data. A function can be createdfrom a formula (e.g. ~ head(.x, 10)).

position

A position adjustment to use on the data for this layer. Thiscan be used in various ways, including to prevent overplotting andimproving the display. The position argument accepts the following:

  • The result of calling a position function, such as position_jitter().This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as astring, strip the function name of the position_ prefix. For example,to use position_jitter(), give the position as "jitter".

  • For more information and other ways to specify the position, see thelayer position documentation.

...

Other arguments passed on to layer()'s params argument. Thesearguments broadly fall into one of 4 categories below. Notably, furtherarguments to the position argument, or aesthetics that are requiredcan not be passed through .... Unknown arguments that are not partof the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixedvalue and apply to the layer as a whole. For example, colour = "red"or linewidth = 3. The geom's documentation has an Aestheticssection that lists the available options. The 'required' aestheticscannot be passed on to the params. Please note that while passingunmapped aesthetics as vectors is technically possible, the order andrequired length is not guaranteed to be parallel to the input data.

  • When constructing a layer usinga stat_*() function, the ... argument can be used to pass onparameters to the geom part of the layer. An example of this isstat_density(geom = "area", outline.type = "both"). The geom'sdocumentation lists which parameters it can accept.

  • Inversely, when constructing a layer using ageom_*() function, the ... argument can be used to pass on parametersto the stat part of the layer. An example of this isgeom_area(stat = "density", adjust = 0.5). The stat's documentationlists which parameters it can accept.

  • The key_glyph argument of layer() may also be passed on through.... This can be one of the functions described askey glyphs, to change the display of the layer in the legend.

na.rm

If FALSE, the default, missing values are removed witha warning. If TRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, and TRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay.

inherit.aes

If FALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g. borders().

binwidth

The width of the bins. Can be specified as a numeric valueor as a function that calculates width from unscaled x. Here, "unscaled x"refers to the original x values in the data, before application of anyscale transformation. When specifying a function along with a groupingstructure, the function will be called once per group.The default is to use the number of bins in bins,covering the range of the data. You should always overridethis value, exploring multiple widths to find the best to illustrate thestories in your data.

The bin width of a date variable is the number of days in each time; thebin width of a time variable is the number of seconds.

bins

Number of bins. Overridden by binwidth. Defaults to 30.

orientation

The orientation of the layer. The default (NA)automatically determines the orientation from the aesthetic mapping. In therare event that this fails it can be given explicitly by setting orientationto either "x" or "y". See the Orientation section for more detail.

geom, stat

Use to override the default connection betweengeom_histogram()/geom_freqpoly() and stat_bin(). For more informationat overriding these connections, see how the stat andgeom arguments work.

center, boundary

bin position specifiers. Only one, center orboundary, may be specified for a single plot. center specifies thecenter of one of the bins. boundary specifies the boundary between twobins. Note that if either is above or below the range of the data, thingswill be shifted by the appropriate integer multiple of binwidth.For example, to center on integers use binwidth = 1 and center = 0, evenif 0 is outside the range of the data. Alternatively, this same alignmentcan be specified with binwidth = 1 and boundary = 0.5, even if 0.5 isoutside the range of the data.

breaks

Alternatively, you can supply a numeric vector givingthe bin boundaries. Overrides binwidth, bins, center,and boundary.

closed

One of "right" or "left" indicating whether rightor left edges of bins are included in the bin.

pad

If TRUE, adds empty bins at either end of x. This ensuresfrequency polygons touch 0. Defaults to FALSE.

Details

stat_bin() is suitable only for continuous x data. If your x data isdiscrete, you probably want to use stat_count().

By default, the underlying computation (stat_bin()) uses 30 bins;this is not a good default, but the idea is to get you experimenting withdifferent number of bins. You can also experiment modifying the binwidth withcenter or boundary arguments. binwidth overrides bins so you should doone change at a time. You may need to look at a few options to uncoverthe full story behind your data.

In addition to geom_histogram(), you can create a histogram plot by usingscale_x_binned() with geom_bar(). This method by default plots tick marksin between each bar.

Orientation

This geom treats each axis differently and, thus, can thus have two orientations. Often the orientation is easy to deduce from a combination of the given mappings and the types of positional scales in use. Thus, ggplot2 will by default try to guess which orientation the layer should have. Under rare circ*mstances, the orientation is ambiguous and guessing may fail. In that case the orientation can be specified directly using the orientation parameter, which can be either "x" or "y". The value gives the axis that the geom should run along, "x" being the default orientation you would expect for the geom.

Aesthetics

geom_histogram() uses the same aesthetics as geom_bar();geom_freqpoly() uses the same aesthetics as geom_line().

Computed variables

These are calculated by the 'stat' part of layers and can be accessed with delayed evaluation.

  • after_stat(count)
    number of points in bin.

  • after_stat(density)
    density of points in bin, scaled to integrate to 1.

  • after_stat(ncount)
    count, scaled to a maximum of 1.

  • after_stat(ndensity)
    density, scaled to a maximum of 1.

  • after_stat(width)
    widths of bins.

Dropped variables

weight

After binning, weights of individual data points (if supplied) are no longer available.

See also

stat_count(), which counts the number of cases at each xposition, without binning. It is suitable for both discrete and continuousx data, whereas stat_bin() is suitable only for continuous x data.

Examples

ggplot(diamonds, aes(carat)) + geom_histogram()#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.Histograms and frequency polygons — geom_freqpoly (2)ggplot(diamonds, aes(carat)) + geom_histogram(binwidth = 0.01)Histograms and frequency polygons — geom_freqpoly (3)ggplot(diamonds, aes(carat)) + geom_histogram(bins = 200)Histograms and frequency polygons — geom_freqpoly (4)# Map values to y to flip the orientationggplot(diamonds, aes(y = carat)) + geom_histogram()#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.Histograms and frequency polygons — geom_freqpoly (5)# For histograms with tick marks between each bin, use `geom_bar()` with# `scale_x_binned()`.ggplot(diamonds, aes(carat)) + geom_bar() + scale_x_binned()Histograms and frequency polygons — geom_freqpoly (6)# Rather than stacking histograms, it's easier to compare frequency# polygonsggplot(diamonds, aes(price, fill = cut)) + geom_histogram(binwidth = 500)Histograms and frequency polygons — geom_freqpoly (7)ggplot(diamonds, aes(price, colour = cut)) + geom_freqpoly(binwidth = 500)Histograms and frequency polygons — geom_freqpoly (8)# To make it easier to compare distributions with very different counts,# put density on the y axis instead of the default countggplot(diamonds, aes(price, after_stat(density), colour = cut)) + geom_freqpoly(binwidth = 500)Histograms and frequency polygons — geom_freqpoly (9)if (require("ggplot2movies")) {# Often we don't want the height of the bar to represent the# count of observations, but the sum of some other variable.# For example, the following plot shows the number of movies# in each rating.m <- ggplot(movies, aes(rating))m + geom_histogram(binwidth = 0.1)# If, however, we want to see the number of votes cast in each# category, we need to weight by the votes variablem + geom_histogram(aes(weight = votes), binwidth = 0.1) + ylab("votes")# For transformed scales, binwidth applies to the transformed data.# The bins have constant width on the transformed scale.m + geom_histogram() + scale_x_log10()m + geom_histogram(binwidth = 0.05) + scale_x_log10()# For transformed coordinate systems, the binwidth applies to the# raw data. The bins have constant width on the original scale.# Using log scales does not work here, because the first# bar is anchored at zero, and so when transformed becomes negative# infinity. This is not a problem when transforming the scales, because# no observations have 0 ratings.m + geom_histogram(boundary = 0) + coord_trans(x = "log10")# Use boundary = 0, to make sure we don't take sqrt of negative valuesm + geom_histogram(boundary = 0) + coord_trans(x = "sqrt")# You can also transform the y axis. Remember that the base of the bars# has value 0, so log transformations are not appropriatem <- ggplot(movies, aes(x = rating))m + geom_histogram(binwidth = 0.5) + scale_y_sqrt()}Histograms and frequency polygons — geom_freqpoly (10)# You can specify a function for calculating binwidth, which is# particularly useful when faceting along variables with# different ranges because the function will be called once per facetggplot(economics_long, aes(value)) + facet_wrap(~variable, scales = 'free_x') + geom_histogram(binwidth = function(x) 2 * IQR(x) / (length(x)^(1/3)))Histograms and frequency polygons — geom_freqpoly (11)
Histograms and frequency polygons — geom_freqpoly (2024)

References

Top Articles
Latest Posts
Article information

Author: Geoffrey Lueilwitz

Last Updated:

Views: 6749

Rating: 5 / 5 (80 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Geoffrey Lueilwitz

Birthday: 1997-03-23

Address: 74183 Thomas Course, Port Micheal, OK 55446-1529

Phone: +13408645881558

Job: Global Representative

Hobby: Sailing, Vehicle restoration, Rowing, Ghost hunting, Scrapbooking, Rugby, Board sports

Introduction: My name is Geoffrey Lueilwitz, I am a zealous, encouraging, sparkling, enchanting, graceful, faithful, nice person who loves writing and wants to share my knowledge and understanding with you.