![]() Now let’s look at the relationship between the length of a mammal’s sleep cycle ( sleep_cycle) and their total rem sleep ( sleep_rem): ggplot(data = msleep, mapping = aes(x = sleep_cycle, y = sleep_rem)) + We do this with coord_cartesian(): ggplot(data = msleep, mapping = aes(x = bodywt, y = sleep_total)) + To deal with that, we can zoom in on the x-axis by restricting its limits. It’s a little difficult to get a sense of the variation between these variables because of the two outliers. Let’s build a scatter plot ( geom_point()) to examine the relationship between sleep_total and body weight bodywt: ggplot(data = msleep, mapping = aes(x = bodywt, y = sleep_total)) + Of course, we can also make plots of two variables by adding a y-axis mapping along with a geom that works well with two variables. If we wanted to build a density plot instead, we could just geom_density() instead of geom_histogram(): ggplot(data = msleep, mapping = aes(x = sleep_total)) + ![]() Geom_histogram: this defines the type of plot to make In this case, we are mapping the x-axis aesthetic to sleep_total Mapping = aes(x = sleep_total): we always map the values we want to plot to an aesthetic ( aes()). Pick better value with `binwidth`.ĭata = msleep: set the data argument equal to the data that you want to plot Geom_histogram() # `stat_bin()` using `bins = 30`. ![]() Let’s make our first plot a histogram of the total amount of sleep for mammals ( sleep_total): ggplot(data = msleep, mapping = aes(x = sleep_total)) + # … with 2 more variables: brainwt, bodywt # 5 Cow Bos herbi Arti… domesticated 4 0.7 0.667 20 # 3 Mounta… Aplo… herbi Rode… nt 14.4 2.4 NA 9.6 # 1 Cheetah Acin… carni Carn… lc 12.1 NA NA 11.9 # name genus vore order conservation sleep_total sleep_rem sleep_cycle awake Here’s what the data looks like: head(msleep) # A tibble: 6 × 11 The ggplot2 package comes with a dataset on mammal’s sleep that we’ll use to practice our plotting. I like to learn by doing, so let’s just start plotting to see this in action, then I’ll explain things. With ggplot we builds plots with two basic functions: ggplot() and geom_*(), where * is a placeholder for a number of different geoms that are available. Let’s load the tidyverse to get started: library(tidyverse) Ggplot2 is one of the primary packages included in R’s tidyverse, so I you already loaded tidyverse then you’re good to go.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |