R ggplot2


Package ggplot2 is a unique system which has many plotting functions. It uses ggplot() function to start the plot, and uses aes() for aesthetic mapping of dataset to the plotting. Other layers such as geom_bar() for a bar plot, coordinate systems etc can be added later as well.

> install.packages("ggplot2",repos="http://cran.r-project.org",dep=TRUE)
> library(ggplot2)
> gg <- ggplot(trees, aes(y=Volume, x=Height)) #trees is a builtin dataset
> gg + geom_bar(stat="identity",color="blue",fill="red")

geom_boxplot() function for box plot:

> gg <- ggplot(CO2, aes(Plant,uptake))#CO2 is a builtin dataset
> gg + geom_boxplot()
> gg + geom_boxplot(aes(color=Type))

geom_point() function for drawing points:

> gg <- ggplot(trees, aes(Height,Volume))
> gg + geom_point(color="green")


geom_histogram() function for drawing histograms:

> gg <- ggplot(CO2,aes(uptake))
> gg + geom_histogram(bins=20,color="green",fill="yellow")


It can also plot time series data. Following code downloads the stock trading data and plots it:

> install.packages("tseries",repos="http://cran.r-project.org",dep=TRUE)
> library(tseries)
> rcl <- get.hist.quote("rcl")  #stocks data of Royal Caribbean Ltd.
time series starts 1993-04-28
time series ends   2020-03-27
> head(rcl)
             Open   High    Low  Close
1993-04-28 9.1250 9.3750 9.0000 9.1250
1993-04-29 9.1250 9.3125 9.1250 9.3125
1993-04-30 9.3750 9.3750 9.1250 9.1875
1993-05-03 9.1250 9.1875 9.0625 9.1875
1993-05-04 9.1875 9.1875 8.9375 9.0625
1993-05-05 9.0000 9.0625 8.8750 8.8750
>autoplot(rcl)

Following is the complete data of the stock RCL:



Plotting functions list of package "ggplot2":

Function
Description
geom_abline
Reference lines: horizontal, vertical, and diagonal
geom_bar
Bar charts
geom_bin2d
Heatmap of 2d bin counts
geom_blank
Draw nothing
geom_boxplot
A box and whiskers plot (in the style of Tukey)
geom_contour
2d contours of a 3d surface
geom_count
Count overlapping points
geom_crossbar
Vertical intervals: lines, crossbars & errorbars
geom_density
Smoothed density estimates
geom_density_2d
Contours of a 2d density estimate
geom_dotplot
Dot plot
geom_errorbarh
Horizontal error bars
geom_freqpoly
Histograms and frequency polygons
geom_hex
Hexagonal heatmap of 2d bin counts
geom_jitter
Jittered points
geom_label
Text
geom_map
Polygons from a reference map
geom_path
Connect observations
geom_point
Points
geom_polygon
Polygons
geom_qq_line
A quantile-quantile plot
geom_quantile
Quantile regression
geom_raster
Rectangles
geom_ribbon
Ribbons and area plots
geom_rug
Rug plots in the margins
geom_segment
Line segments and curves
geom_smooth
Smoothed conditional means
geom_spoke
Line segments parameterised by location, direction and distance
geom_violin
Violin plot
endmemo.com © 2024  | Terms of Use | Privacy | Home