What Do I Need to Do to Read in a Large Data File in R
Data visualisation
Introduction
"The elementary graph has brought more information to the data analyst's mind than any other device." — John Tukey
This chapter will teach you how to visualise your data using ggplot2. R has several systems for making graphs, but ggplot2 is one of the near elegant and most versatile. ggplot2 implements the grammar of graphics, a coherent system for describing and building graphs. With ggplot2, you tin can do more faster past learning one system and applying information technology in many places.
If you'd similar to larn more than virtually the theoretical underpinnings of ggplot2 before you start, I'd recommend reading "The Layered Grammar of Graphics", http://vita.had.co.nz/papers/layered-grammar.pdf.
Prerequisites
This affiliate focusses on ggplot2, 1 of the cadre members of the tidyverse. To access the datasets, assist pages, and functions that we will use in this affiliate, load the tidyverse by running this code:
library ( tidyverse ) #> ── Attaching packages ─────────────────────────────────────── tidyverse one.3.0 ── #> ✔ ggplot2 three.iii.ii ✔ purrr 0.3.4 #> ✔ tibble 3.0.iii ✔ dplyr 1.0.2 #> ✔ tidyr i.one.2 ✔ stringr ane.four.0 #> ✔ readr 1.four.0 ✔ forcats 0.5.0 #> ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ── #> ✖ dplyr::filter() masks stats::filter() #> ✖ dplyr::lag() masks stats::lag() That one line of lawmaking loads the core tidyverse; packages which you volition use in near every information analysis. Information technology also tells you which functions from the tidyverse conflict with functions in base R (or from other packages you might have loaded).
If you run this code and become the mistake bulletin "there is no parcel called 'tidyverse'", you'll need to first install information technology, then run library() once again.
You lot but need to install a packet once, just you need to reload it every time you beginning a new session.
If nosotros need to be explicit most where a function (or dataset) comes from, we'll employ the special course package::office(). For instance, ggplot2::ggplot() tells you explicitly that we're using the ggplot() part from the ggplot2 packet.
Start steps
Permit'southward use our showtime graph to answer a question: Do cars with big engines use more fuel than cars with small engines? Yous probably already accept an reply, but try to make your reply precise. What does the relationship between engine size and fuel efficiency look like? Is information technology positive? Negative? Linear? Nonlinear?
The mpg data frame
You can examination your answer with the mpg data frame found in ggplot2 (aka ggplot2::mpg). A data frame is a rectangular collection of variables (in the columns) and observations (in the rows). mpg contains observations collected by the US Ecology Protection Agency on 38 models of car.
mpg #> # A tibble: 234 10 11 #> manufacturer model displ twelvemonth cyl trans drv cty hwy fl class #> <chr> <chr> <dbl> <int> <int> <chr> <chr> <int> <int> <chr> <chr> #> one audi a4 one.eight 1999 4 machine(l5) f 18 29 p compa… #> 2 audi a4 1.eight 1999 4 transmission(m5) f 21 29 p compa… #> three audi a4 ii 2008 iv manual(m6) f xx 31 p compa… #> 4 audi a4 two 2008 4 auto(av) f 21 xxx p compa… #> 5 audi a4 2.8 1999 half dozen auto(l5) f 16 26 p compa… #> 6 audi a4 2.8 1999 6 transmission(m5) f 18 26 p compa… #> # … with 228 more rows Amid the variables in mpg are:
-
displ, a car's engine size, in litres. -
hwy, a car's fuel efficiency on the highway, in miles per gallon (mpg). A automobile with a depression fuel efficiency consumes more fuel than a car with a high fuel efficiency when they travel the same altitude.
To acquire more than about mpg, open its help folio past running ?mpg.
Creating a ggplot
To plot mpg, run this code to put displ on the 10-axis and hwy on the y-axis:
ggplot (data = mpg ) + geom_point (mapping = aes (x = displ, y = hwy ) )
The plot shows a negative relationship between engine size (displ) and fuel efficiency (hwy). In other words, cars with big engines use more fuel. Does this confirm or abnegate your hypothesis about fuel efficiency and engine size?
With ggplot2, yous begin a plot with the role ggplot(). ggplot() creates a coordinate organization that y'all tin can add layers to. The get-go statement of ggplot() is the dataset to apply in the graph. So ggplot(data = mpg) creates an empty graph, merely information technology's not very interesting and so I'g not going to show it hither.
You lot complete your graph by calculation one or more layers to ggplot(). The role geom_point() adds a layer of points to your plot, which creates a scatterplot. ggplot2 comes with many geom functions that each add a dissimilar type of layer to a plot. You'll acquire a whole bunch of them throughout this affiliate.
Each geom function in ggplot2 takes a mapping statement. This defines how variables in your dataset are mapped to visual properties. The mapping statement is always paired with aes(), and the x and y arguments of aes() specify which variables to map to the 10 and y axes. ggplot2 looks for the mapped variables in the information argument, in this case, mpg.
A graphing template
Let's turn this code into a reusable template for making graphs with ggplot2. To make a graph, replace the bracketed sections in the lawmaking below with a dataset, a geom function, or a collection of mappings.
ggplot(data = <DATA>) + <GEOM_FUNCTION>(mapping = aes(<MAPPINGS>)) The balance of this chapter will show you lot how to consummate and extend this template to brand different types of graphs. Nosotros volition begin with the <MAPPINGS> component.
Exercises
-
Run
ggplot(data = mpg). What exercise yous see? -
How many rows are in
mpg? How many columns? -
What does the
drvvariable describe? Read the assist for?mpgto discover out. -
Make a scatterplot of
hwyvscyl. -
What happens if you make a scatterplot of
classvsdrv? Why is the plot non useful?
Artful mappings
"The greatest value of a picture show is when it forces the states to find what we never expected to see." — John Tukey
In the plot below, ane group of points (highlighted in ruby-red) seems to fall outside of the linear trend. These cars take a higher mileage than you might await. How can you explain these cars?
Let's hypothesize that the cars are hybrids. One way to test this hypothesis is to expect at the form value for each car. The form variable of the mpg dataset classifies cars into groups such as compact, midsize, and SUV. If the outlying points are hybrids, they should be classified as meaty cars or, mayhap, subcompact cars (keep in heed that this data was collected before hybrid trucks and SUVs became pop).
You tin can add a 3rd variable, like course, to a 2 dimensional scatterplot by mapping it to an aesthetic. An artful is a visual property of the objects in your plot. Aesthetics include things like the size, the shape, or the colour of your points. Yous can display a signal (like the one beneath) in different means by changing the values of its aesthetic backdrop. Since we already use the word "value" to describe data, permit's use the word "level" to draw aesthetic properties. Here we modify the levels of a point's size, shape, and color to make the point small, triangular, or blueish:
You can convey data near your data by mapping the aesthetics in your plot to the variables in your dataset. For example, you lot tin map the colors of your points to the class variable to reveal the grade of each machine.
ggplot (data = mpg ) + geom_point (mapping = aes (x = displ, y = hwy, colour = class ) )
(If you adopt British English, like Hadley, you can apply colour instead of color.)
To map an aesthetic to a variable, associate the name of the aesthetic to the name of the variable inside aes(). ggplot2 will automatically assign a unique level of the artful (here a unique colour) to each unique value of the variable, a process known equally scaling. ggplot2 will also add together a legend that explains which levels correspond to which values.
The colors reveal that many of the unusual points are two-seater cars. These cars don't seem like hybrids, and are, in fact, sports cars! Sports cars have large engines similar SUVs and pickup trucks, but small bodies like midsize and compact cars, which improves their gas mileage. In hindsight, these cars were unlikely to be hybrids since they have big engines.
In the in a higher place instance, we mapped class to the color artful, but we could take mapped class to the size aesthetic in the aforementioned mode. In this case, the verbal size of each indicate would reveal its form affiliation. We get a warning here, because mapping an unordered variable (class) to an ordered aesthetic (size) is non a good thought.
ggplot (data = mpg ) + geom_point (mapping = aes (ten = displ, y = hwy, size = class ) ) #> Alert: Using size for a discrete variable is not brash.
Or we could have mapped class to the alpha artful, which controls the transparency of the points, or to the shape artful, which controls the shape of the points.
# Left ggplot (information = mpg ) + geom_point (mapping = aes (10 = displ, y = hwy, alpha = grade ) ) # Correct ggplot (information = mpg ) + geom_point (mapping = aes (x = displ, y = hwy, shape = class ) )
What happened to the SUVs? ggplot2 will only use half dozen shapes at a fourth dimension. By default, additional groups will go unplotted when you lot employ the shape aesthetic.
For each artful, yous utilise aes() to associate the proper noun of the aesthetic with a variable to display. The aes() function gathers together each of the aesthetic mappings used by a layer and passes them to the layer'due south mapping argument. The syntax highlights a useful insight about x and y: the x and y locations of a indicate are themselves aesthetics, visual properties that you tin map to variables to display information about the data.
Once you map an aesthetic, ggplot2 takes care of the rest. Information technology selects a reasonable scale to use with the aesthetic, and it constructs a legend that explains the mapping between levels and values. For x and y aesthetics, ggplot2 does non create a legend, merely it creates an centrality line with tick marks and a label. The axis line acts as a fable; it explains the mapping between locations and values.
You lot can also gear up the artful properties of your geom manually. For example, we can make all of the points in our plot blue:
ggplot (information = mpg ) + geom_point (mapping = aes (10 = displ, y = hwy ), colour = "bluish" )
Here, the color doesn't convey data nearly a variable, only only changes the appearance of the plot. To set an aesthetic manually, set the aesthetic past name as an argument of your geom part; i.e. it goes outside of aes(). Yous'll need to pick a level that makes sense for that aesthetic:
-
The name of a color every bit a character string.
-
The size of a signal in mm.
-
The shape of a point as a number, every bit shown in Figure 3.1.
Effigy iii.ane: R has 25 built in shapes that are identified by numbers. There are some seeming duplicates: for case, 0, 15, and 22 are all squares. The difference comes from the interaction of the color and make full aesthetics. The hollow shapes (0–xiv) accept a border adamant by colour; the solid shapes (15–20) are filled with color; the filled shapes (21–24) have a border of color and are filled with fill.
Exercises
-
What's gone wrong with this lawmaking? Why are the points not bluish?
ggplot (data = mpg ) + geom_point (mapping = aes (ten = displ, y = hwy, color = "blue" ) )
-
Which variables in
mpgare categorical? Which variables are continuous? (Hint: type?mpgto read the documentation for the dataset). How tin yous run across this information when you runmpg? -
Map a continuous variable to
color,size, andshape. How exercise these aesthetics behave differently for categorical vs. continuous variables? -
What happens if you map the same variable to multiple aesthetics?
-
What does the
strokeaesthetic do? What shapes does information technology work with? (Hint: use?geom_point) -
What happens if you map an aesthetic to something other than a variable proper noun, similar
aes(colour = displ < five)? Note, you'll also need to specify x and y.
Common issues
As you showtime to run R lawmaking, yous're likely to run across problems. Don't worry — it happens to everyone. I take been writing R code for years, and every mean solar day I however write code that doesn't piece of work!
Start by advisedly comparing the lawmaking that you lot're running to the code in the volume. R is extremely picky, and a misplaced character can make all the difference. Make sure that every ( is matched with a ) and every " is paired with another ". Sometimes you'll run the code and nothing happens. Check the left-manus of your console: if it's a +, information technology means that R doesn't call up you've typed a complete expression and information technology'south waiting for you to finish it. In this case, it's usually easy to starting time from scratch again by pressing ESCAPE to arrest processing the current control.
I common problem when creating ggplot2 graphics is to put the + in the wrong place: information technology has to come at the end of the line, not the get-go. In other words, make sure you haven't accidentally written lawmaking like this:
ggplot (information = mpg ) + geom_point (mapping = aes (x = displ, y = hwy ) ) If you're still stuck, try the help. You tin go assistance about any R function by running ?function_name in the console, or selecting the function name and pressing F1 in RStudio. Don't worry if the help doesn't seem that helpful - instead skip down to the examples and look for code that matches what you're trying to do.
If that doesn't help, carefully read the mistake message. Sometimes the answer will be buried at that place! Just when you're new to R, the answer might be in the error message but you don't yet know how to sympathize it. Some other cracking tool is Google: try googling the error message, as it's likely someone else has had the same problem, and has gotten help online.
Facets
One style to add together additional variables is with aesthetics. Another way, particularly useful for categorical variables, is to split your plot into facets, subplots that each brandish one subset of the data.
To facet your plot by a single variable, use facet_wrap(). The first argument of facet_wrap() should be a formula, which you create with ~ followed past a variable name (here "formula" is the name of a data structure in R, not a synonym for "equation"). The variable that you laissez passer to facet_wrap() should exist discrete.
ggplot (data = mpg ) + geom_point (mapping = aes (x = displ, y = hwy ) ) + facet_wrap ( ~ course, nrow = 2 )
To facet your plot on the combination of ii variables, add facet_grid() to your plot call. The starting time argument of facet_grid() is likewise a formula. This fourth dimension the formula should contain ii variable names separated past a ~.
ggplot (information = mpg ) + geom_point (mapping = aes (x = displ, y = hwy ) ) + facet_grid ( drv ~ cyl )
If you adopt to not facet in the rows or columns dimension, use a . instead of a variable proper noun, due east.g.+ facet_grid(. ~ cyl).
Exercises
-
What happens if you facet on a continuous variable?
-
What exercise the empty cells in plot with
facet_grid(drv ~ cyl)mean? How do they chronicle to this plot?ggplot (data = mpg ) + geom_point (mapping = aes (ten = drv, y = cyl ) ) -
What plots does the following code make? What does
.do?ggplot (information = mpg ) + geom_point (mapping = aes (x = displ, y = hwy ) ) + facet_grid ( drv ~ . ) ggplot (information = mpg ) + geom_point (mapping = aes (x = displ, y = hwy ) ) + facet_grid ( . ~ cyl ) -
Take the first faceted plot in this department:
ggplot (data = mpg ) + geom_point (mapping = aes (x = displ, y = hwy ) ) + facet_wrap ( ~ class, nrow = 2 )What are the advantages to using faceting instead of the colour aesthetic? What are the disadvantages? How might the residual modify if y'all had a larger dataset?
-
Read
?facet_wrap. What doesnrowdo? What doesncolpractice? What other options control the layout of the individual panels? Why doesn'tfacet_grid()takenrowandncolarguments? -
When using
facet_grid()yous should commonly put the variable with more unique levels in the columns. Why?
Geometric objects
How are these 2 plots similar?
Both plots comprise the same ten variable, the same y variable, and both describe the same data. Just the plots are not identical. Each plot uses a dissimilar visual object to correspond the information. In ggplot2 syntax, we say that they use dissimilar geoms.
A geom is the geometrical object that a plot uses to stand for information. People ofttimes describe plots past the blazon of geom that the plot uses. For case, bar charts use bar geoms, line charts utilise line geoms, boxplots utilise boxplot geoms, and and so on. Scatterplots intermission the trend; they use the signal geom. As we encounter above, you can use different geoms to plot the same information. The plot on the left uses the bespeak geom, and the plot on the right uses the smooth geom, a smoothen line fitted to the data.
To change the geom in your plot, change the geom function that you lot add together to ggplot(). For case, to make the plots above, you lot can use this code:
# left ggplot (data = mpg ) + geom_point (mapping = aes (ten = displ, y = hwy ) ) # right ggplot (data = mpg ) + geom_smooth (mapping = aes (x = displ, y = hwy ) ) Every geom part in ggplot2 takes a mapping statement. However, not every artful works with every geom. Y'all could set the shape of a signal, just you couldn't set the "shape" of a line. On the other hand, y'all could set the linetype of a line. geom_smooth() will depict a unlike line, with a different linetype, for each unique value of the variable that you map to linetype.
ggplot (information = mpg ) + geom_smooth (mapping = aes (x = displ, y = hwy, linetype = drv ) )
Here geom_smooth() separates the cars into three lines based on their drv value, which describes a car's drivetrain. One line describes all of the points with a 4 value, 1 line describes all of the points with an f value, and one line describes all of the points with an r value. Hither, four stands for four-wheel drive, f for front-wheel drive, and r for rear-bicycle bulldoze.
If this sounds strange, we can make it more clear by overlaying the lines on elevation of the raw data and then coloring everything co-ordinate to drv.
Notice that this plot contains two geoms in the aforementioned graph! If this makes y'all excited, buckle upwards. Nosotros will larn how to place multiple geoms in the same plot very before long.
ggplot2 provides over 40 geoms, and extension packages provide fifty-fifty more than (see https://exts.ggplot2.tidyverse.org/gallery/ for a sampling). The best fashion to become a comprehensive overview is the ggplot2 cheatsheet, which you can notice at http://rstudio.com/resources/cheatsheets. To learn more about any single geom, use assistance: ?geom_smooth.
Many geoms, like geom_smooth(), use a unmarried geometric object to brandish multiple rows of data. For these geoms, you can set up the grouping aesthetic to a chiselled variable to describe multiple objects. ggplot2 will draw a separate object for each unique value of the grouping variable. In practice, ggplot2 will automatically group the data for these geoms whenever you map an aesthetic to a discrete variable (as in the linetype example). It is user-friendly to rely on this feature because the group aesthetic by itself does not add together a legend or distinguishing features to the geoms.
ggplot (data = mpg ) + geom_smooth (mapping = aes (10 = displ, y = hwy ) ) ggplot (information = mpg ) + geom_smooth (mapping = aes (x = displ, y = hwy, group = drv ) ) ggplot (information = mpg ) + geom_smooth ( mapping = aes (x = displ, y = hwy, colour = drv ), show.legend = False )
To display multiple geoms in the aforementioned plot, add multiple geom functions to ggplot():
ggplot (data = mpg ) + geom_point (mapping = aes (x = displ, y = hwy ) ) + geom_smooth (mapping = aes (ten = displ, y = hwy ) )
This, yet, introduces some duplication in our code. Imagine if yous wanted to change the y-axis to display cty instead of hwy. You'd demand to modify the variable in 2 places, and you lot might forget to update one. Yous tin avoid this type of repetition by passing a set of mappings to ggplot(). ggplot2 will care for these mappings as global mappings that apply to each geom in the graph. In other words, this code will produce the same plot as the previous code:
ggplot (data = mpg, mapping = aes (x = displ, y = hwy ) ) + geom_point ( ) + geom_smooth ( ) If you lot place mappings in a geom function, ggplot2 volition treat them as local mappings for the layer. It will employ these mappings to extend or overwrite the global mappings for that layer only. This makes it possible to brandish different aesthetics in different layers.
ggplot (data = mpg, mapping = aes (ten = displ, y = hwy ) ) + geom_point (mapping = aes (color = grade ) ) + geom_smooth ( )
Y'all can use the same idea to specify unlike information for each layer. Here, our smooth line displays just a subset of the mpg dataset, the subcompact cars. The local data argument in geom_smooth() overrides the global data statement in ggplot() for that layer only.
ggplot (data = mpg, mapping = aes (ten = displ, y = hwy ) ) + geom_point (mapping = aes (color = grade ) ) + geom_smooth (data = filter ( mpg, class == "subcompact" ), se = Simulated )
(You'll learn how filter() works in the chapter on data transformations: for at present, merely know that this command selects merely the subcompact cars.)
Exercises
-
What geom would you use to draw a line chart? A boxplot? A histogram? An area nautical chart?
-
Run this lawmaking in your caput and predict what the output will expect like. Then, run the code in R and check your predictions.
ggplot (data = mpg, mapping = aes (x = displ, y = hwy, color = drv ) ) + geom_point ( ) + geom_smooth (se = FALSE ) -
What does
testify.legend = FALSEdo? What happens if you remove it?
Why do you think I used it earlier in the chapter? -
What does the
seargument togeom_smooth()do? -
Will these 2 graphs wait unlike? Why/why non?
ggplot (data = mpg, mapping = aes (x = displ, y = hwy ) ) + geom_point ( ) + geom_smooth ( ) ggplot ( ) + geom_point (data = mpg, mapping = aes (ten = displ, y = hwy ) ) + geom_smooth (information = mpg, mapping = aes (10 = displ, y = hwy ) ) -
Recreate the R code necessary to generate the following graphs.
Statistical transformations
Next, let's have a look at a bar chart. Bar charts seem simple, but they are interesting considering they reveal something subtle near plots. Consider a basic bar chart, equally fatigued with geom_bar(). The following chart displays the total number of diamonds in the diamonds dataset, grouped by cut. The diamonds dataset comes in ggplot2 and contains information nearly ~54,000 diamonds, including the price, carat, color, clarity, and cut of each diamond. The chart shows that more than diamonds are available with high quality cuts than with low quality cuts.
ggplot (data = diamonds ) + geom_bar (mapping = aes (10 = cut ) )
On the 10-axis, the nautical chart displays cut, a variable from diamonds. On the y-axis, it displays count, but count is non a variable in diamonds! Where does count come from? Many graphs, like scatterplots, plot the raw values of your dataset. Other graphs, like bar charts, summate new values to plot:
-
bar charts, histograms, and frequency polygons bin your data and so plot bin counts, the number of points that fall in each bin.
-
smoothers fit a model to your information and and so plot predictions from the model.
-
boxplots compute a robust summary of the distribution so brandish a specially formatted box.
The algorithm used to summate new values for a graph is called a stat, brusque for statistical transformation. The effigy below describes how this process works with geom_bar().
Y'all can learn which stat a geom uses by inspecting the default value for the stat argument. For example, ?geom_bar shows that the default value for stat is "count", which means that geom_bar() uses stat_count(). stat_count() is documented on the same folio equally geom_bar(), and if you gyre down you can notice a section chosen "Computed variables". That describes how it computes two new variables: count and prop.
You can generally use geoms and stats interchangeably. For example, you can recreate the previous plot using stat_count() instead of geom_bar():
ggplot (data = diamonds ) + stat_count (mapping = aes (x = cut ) )
This works because every geom has a default stat; and every stat has a default geom. This means that yous tin typically utilise geoms without worrying virtually the underlying statistical transformation. There are 3 reasons you might demand to use a stat explicitly:
-
Yous might want to override the default stat. In the code below, I change the stat of
geom_bar()from count (the default) to identity. This lets me map the superlative of the bars to the raw values of a \(y\) variable. Unfortunately when people talk almost bar charts casually, they might exist referring to this type of bar nautical chart, where the height of the bar is already present in the data, or the previous bar chart where the height of the bar is generated by counting rows.demo <- tribble ( ~ cutting, ~ freq, "Fair", 1610, "Good", 4906, "Very Good", 12082, "Premium", 13791, "Ideal", 21551 ) ggplot (information = demo ) + geom_bar (mapping = aes (x = cut, y = freq ), stat = "identity" )
(Don't worry that you haven't seen
<-ortribble()before. You might be able to guess at their meaning from the context, and y'all'll larn exactly what they do shortly!) -
You lot might want to override the default mapping from transformed variables to aesthetics. For example, you might want to brandish a bar nautical chart of proportion, rather than count:
ggplot (information = diamonds ) + geom_bar (mapping = aes (ten = cut, y = stat ( prop ), group = one ) )
To discover the variables computed past the stat, look for the help section titled "computed variables".
-
You might want to draw greater attention to the statistical transformation in your code. For example, you might use
stat_summary(), which summarises the y values for each unique x value, to draw attention to the summary that you're computing:ggplot (data = diamonds ) + stat_summary ( mapping = aes (x = cutting, y = depth ), fun.min = min, fun.max = max, fun = median )
ggplot2 provides over 20 stats for yous to apply. Each stat is a function, and then you can get assistance in the usual mode, eastward.one thousand.?stat_bin. To see a complete list of stats, try the ggplot2 cheatsheet.
Exercises
-
What is the default geom associated with
stat_summary()? How could you rewrite the previous plot to use that geom office instead of the stat function? -
What does
geom_col()do? How is it dissimilar togeom_bar()? -
Virtually geoms and stats come in pairs that are almost always used in concert. Read through the documentation and brand a list of all the pairs. What practice they take in common?
-
What variables does
stat_smooth()compute? What parameters command its behaviour? -
In our proportion bar chart, we need to set
group = 1. Why? In other words what is the problem with these two graphs?ggplot (data = diamonds ) + geom_bar (mapping = aes (x = cutting, y = after_stat ( prop ) ) ) ggplot (data = diamonds ) + geom_bar (mapping = aes (x = cutting, fill = colour, y = after_stat ( prop ) ) )
Position adjustments
There's ane more piece of magic associated with bar charts. You tin colour a bar chart using either the color aesthetic, or, more usefully, fill:
ggplot (data = diamonds ) + geom_bar (mapping = aes (x = cutting, color = cut ) ) ggplot (information = diamonds ) + geom_bar (mapping = aes (x = cut, make full = cut ) )
Note what happens if you map the fill up aesthetic to another variable, like clarity: the bars are automatically stacked. Each colored rectangle represents a combination of cutting and clarity.
ggplot (data = diamonds ) + geom_bar (mapping = aes (x = cut, fill = clarity ) )
The stacking is performed automatically past the position aligning specified by the position statement. If you don't desire a stacked bar chart, you can use ane of 3 other options: "identity", "dodge" or "make full".
-
position = "identity"will identify each object exactly where it falls in the context of the graph. This is non very useful for bars, considering information technology overlaps them. To see that overlapping we either demand to make the bars slightly transparent past settingalphato a minor value, or completely transparent by settingfill = NA.ggplot (data = diamonds, mapping = aes (ten = cutting, fill = clarity ) ) + geom_bar (alpha = 1 / 5, position = "identity" ) ggplot (data = diamonds, mapping = aes (x = cutting, colour = clarity ) ) + geom_bar (fill = NA, position = "identity" )
The identity position aligning is more than useful for second geoms, like points, where it is the default.
-
position = "fill"works like stacking, merely makes each set of stacked bars the aforementioned height. This makes it easier to compare proportions beyond groups.ggplot (data = diamonds ) + geom_bar (mapping = aes (ten = cut, fill = clarity ), position = "fill" )
-
position = "dodge"places overlapping objects directly beside ane another. This makes it easier to compare private values.ggplot (data = diamonds ) + geom_bar (mapping = aes (10 = cutting, fill up = clarity ), position = "dodge" )
In that location's i other type of aligning that's not useful for bar charts, only it tin exist very useful for scatterplots. Recall our first scatterplot. Did you detect that the plot displays just 126 points, even though there are 234 observations in the dataset?
The values of hwy and displ are rounded so the points appear on a grid and many points overlap each other. This trouble is known as overplotting. This arrangement makes it hard to run into where the mass of the information is. Are the information points spread equally throughout the graph, or is there one special combination of hwy and displ that contains 109 values?
You can avoid this gridding by setting the position adjustment to "jitter". position = "jitter" adds a small amount of random dissonance to each point. This spreads the points out because no two points are likely to receive the same corporeality of random dissonance.
ggplot (information = mpg ) + geom_point (mapping = aes (x = displ, y = hwy ), position = "jitter" )
Calculation randomness seems like a strange style to improve your plot, but while it makes your graph less accurate at small scales, information technology makes your graph more than revealing at big scales. Because this is such a useful operation, ggplot2 comes with a shorthand for geom_point(position = "jitter"): geom_jitter().
To learn more about a position aligning, await up the aid folio associated with each adjustment: ?position_dodge, ?position_fill, ?position_identity, ?position_jitter, and ?position_stack.
Exercises
-
What is the trouble with this plot? How could you meliorate it?
ggplot (data = mpg, mapping = aes (x = cty, y = hwy ) ) + geom_point ( )
-
What parameters to
geom_jitter()control the corporeality of jittering? -
Compare and contrast
geom_jitter()withgeom_count(). -
What's the default position aligning for
geom_boxplot()? Create a visualisation of thempgdataset that demonstrates it.
Coordinate systems
Coordinate systems are probably the most complicated part of ggplot2. The default coordinate system is the Cartesian coordinate organisation where the x and y positions human action independently to determine the location of each signal. There are a number of other coordinate systems that are occasionally helpful.
-
coord_flip()switches the 10 and y axes. This is useful (for example), if you want horizontal boxplots. It's also useful for long labels: information technology'south hard to get them to fit without overlapping on the ten-axis.ggplot (information = mpg, mapping = aes (x = course, y = hwy ) ) + geom_boxplot ( ) ggplot (data = mpg, mapping = aes (x = class, y = hwy ) ) + geom_boxplot ( ) + coord_flip ( )
-
coord_quickmap()sets the aspect ratio correctly for maps. This is very of import if you're plotting spatial data with ggplot2 (which unfortunately nosotros don't have the infinite to encompass in this book).nz <- map_data ( "nz" ) ggplot ( nz, aes ( long, lat, group = group ) ) + geom_polygon (fill = "white", colour = "black" ) ggplot ( nz, aes ( long, lat, group = grouping ) ) + geom_polygon (make full = "white", colour = "black" ) + coord_quickmap ( )
-
coord_polar()uses polar coordinates. Polar coordinates reveal an interesting connection betwixt a bar chart and a Coxcomb chart.bar <- ggplot (data = diamonds ) + geom_bar ( mapping = aes (x = cutting, fill = cutting ), prove.legend = FALSE, width = ane ) + theme (aspect.ratio = 1 ) + labs (x = Nil, y = Cypher ) bar + coord_flip ( ) bar + coord_polar ( )
Exercises
-
Plough a stacked bar nautical chart into a pie chart using
coord_polar(). -
What does
labs()do? Read the documentation. -
What's the difference between
coord_quickmap()andcoord_map()? -
What does the plot below tell you lot about the relationship betwixt city and highway mpg? Why is
coord_fixed()important? What doesgeom_abline()do?ggplot (data = mpg, mapping = aes (x = cty, y = hwy ) ) + geom_point ( ) + geom_abline ( ) + coord_fixed ( )
The layered grammar of graphics
In the previous sections, you learned much more than than how to make scatterplots, bar charts, and boxplots. Yous learned a foundation that y'all can apply to make any blazon of plot with ggplot2. To see this, let'southward add position adjustments, stats, coordinate systems, and faceting to our code template:
ggplot(data = <DATA>) + <GEOM_FUNCTION>( mapping = aes(<MAPPINGS>), stat = <STAT>, position = <POSITION> ) + <COORDINATE_FUNCTION> + <FACET_FUNCTION> Our new template takes seven parameters, the bracketed words that appear in the template. In practice, y'all rarely need to supply all seven parameters to make a graph because ggplot2 will provide useful defaults for everything except the data, the mappings, and the geom function.
The seven parameters in the template compose the grammar of graphics, a formal system for edifice plots. The grammar of graphics is based on the insight that you can uniquely describe any plot as a combination of a dataset, a geom, a set of mappings, a stat, a position adjustment, a coordinate system, and a faceting scheme.
To see how this works, consider how you could build a bones plot from scratch: you could start with a dataset and then transform it into the data that you want to display (with a stat).
Adjacent, you could cull a geometric object to represent each observation in the transformed information. You lot could then use the aesthetic properties of the geoms to represent variables in the data. You would map the values of each variable to the levels of an aesthetic.
You'd and then select a coordinate organisation to place the geoms into. You lot'd use the location of the objects (which is itself an aesthetic property) to display the values of the x and y variables. At that signal, you would have a consummate graph, merely you could further adjust the positions of the geoms within the coordinate organization (a position adjustment) or divide the graph into subplots (faceting). You could also extend the plot by adding one or more than additional layers, where each boosted layer uses a dataset, a geom, a fix of mappings, a stat, and a position adjustment.
You could employ this method to build any plot that y'all imagine. In other words, you lot can use the code template that you've learned in this chapter to build hundreds of thousands of unique plots.
Source: https://r4ds.had.co.nz/data-visualisation.html
0 Response to "What Do I Need to Do to Read in a Large Data File in R"
Postar um comentário