Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
ggplot2 Essentials
ggplot2 Essentials

ggplot2 Essentials: Explore the full range of ggplot2 plotting capabilities to create meaningful and spectacular graphs

eBook
€10.99 €16.99
Paperback
€20.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

ggplot2 Essentials

Chapter 2. Getting Started

In this chapter, we will go through the main plot types that can be realized with ggplot2. In the examples, we will use the qplot() basic function so that you have a reference for how to realize such plots, even if you are not interested in a more detailed personalization of the graph details. We will see how to realize the following plots:

  • Histograms and density plots
  • Bar charts
  • Boxplots
  • Scatterplots
  • Time series plots
  • Bubble charts and dot plots

In Chapter 3, The Layers and Grammar of Graphics, we will describe the use of the ggplot function, and in the equivalent coding between qplot and ggplot, we will also discuss how to realize the plots with such a sophisticated function.

General aspects

The qplot (quick plot) function is a basic high-level function of ggplot2. The general syntax that you should use with this function is the following:

qplot(x, y, data, color, shape, size, facets, geom, stat)

The definitions of the various components of this function are as follows:

  • x and y: These represent the variables to plot (y is optional, with a default value of NULL).
  • data: This defines the dataset containing the variables.
  • color, shape and size: These are the aesthetic arguments that can be mapped on additional variables.
  • facets: This defines the optional faceting of the plot based on one variable contained in the dataset.
  • geom: This allows you to select the actual visualization of the data, which, basically, will define the plot that will be generated. The possible values are point, line, and boxplot, and we will see several different examples in the next pages.
  • stat: This defines the statistics to be used for the data.

These arguments represent the most important options...

Histograms and density plots

Histograms are plots used to explore how one or more quantitative variables are distributed. To show some examples of histograms, we will use the iris data. This dataset contains measurements in centimetres of the length and width variables of the sepal and petal, and these measurements are available for 50 flowers from each of three species of iris: Iris setosa, versicolor, and virginica. You can get more details upon running ?iris.

The geometric attribute used to produce histograms is defined simply by specifying geom="histogram" in the qplot function. This default histogram will represent the variable specified in the function on the x axis, while the y axis will represent the number of elements in each bin. One other very useful way of representing distributions is to look at the kernel density function, which represents an approximation of the distribution of the data as a continuous function instead of different bins, by estimating the probability...

Bar charts

Bar charts are usually used to explore how one (or more) categorical variables are distributed. In qplot(), this is done using the geom option bar. This geometry counts the number of occurrences of each factor variable, which appears in the data. To show an example of the bar chart, we will use the movies dataset, which is included within the ggplot2 package. We have already seen how to recall the dataset included with the basic installation of R, but if you are interested in the list of datasets within a specific package (ggplot2 in this case), you can use the following code:

require(ggplot2)       ## Load ggplot2 if needed
data(package="ggplot2")  ## List of dataset within ggplot2

The movies dataset contains information about movies, including the rating, from the http://imdb.com/ website. You can get a more detailed description in the help page of the dataset.

This dataset contains different variables but, for our example, we will not need all of them, so let´...

Boxplots

Box plots, also known as box-and-whisker plots, are a type of plot used to depict a distribution by representing its quartile values. In such plots, the upper and lower sides of the box represent the twenty-fifth and seventy-fifth percentiles (also called the first and third quartiles), while the horizontal line within the box represents the median of the data. The difference between the first and third quartiles is defined as Inter-Quartile Range (IQR), and it is often used as a measure of statistical dispersion of a distribution. The upper whisker represents the higher values up to 1.5*IQR of the upper quartile, while the lower whisker represents lower values within 1.5*IQR of the lower quartile. The pieces of data not in the whisker range are plotted as points and are defined as outliers. You can get additional details and references in the package website shown at the end of the chapter.

In this section, we will see some examples of boxplots using the dataset created in the...

Scatterplots

Scatterplots are probably among the most common plots, since they are frequently used to display the relationship between two quantitative variables. When two variables are provided, ggplot2 will make a scatterplot by default. Now that you have already acquired some experience from the previous sections of this chapter, the representation of the scatter plot will be quite straightforward for you.

For our example on how to build a scatterplot, we will use a dataset called ToothGrowth, which is available in the base R installation. Reported in this dataset are measurements of the length of the teeth of 10 guinea pigs for three different doses of vitamin C (0.5, 1, and 2 mg). It is delivered in two different ways—as orange juice or as ascorbic acid (a compound with vitamin C activity). You can find details on the dataset help page at ?ToothGrowth.

We are interested in seeing how the length of the teeth changed for each different dose. We are not able to distinguish the different...

General aspects


The qplot (quick plot) function is a basic high-level function of ggplot2. The general syntax that you should use with this function is the following:

qplot(x, y, data, color, shape, size, facets, geom, stat)

The definitions of the various components of this function are as follows:

  • x and y: These represent the variables to plot (y is optional, with a default value of NULL).

  • data: This defines the dataset containing the variables.

  • color, shape and size: These are the aesthetic arguments that can be mapped on additional variables.

  • facets: This defines the optional faceting of the plot based on one variable contained in the dataset.

  • geom: This allows you to select the actual visualization of the data, which, basically, will define the plot that will be generated. The possible values are point, line, and boxplot, and we will see several different examples in the next pages.

  • stat: This defines the statistics to be used for the data.

These arguments represent the most important options...

Histograms and density plots


Histograms are plots used to explore how one or more quantitative variables are distributed. To show some examples of histograms, we will use the iris data. This dataset contains measurements in centimetres of the length and width variables of the sepal and petal, and these measurements are available for 50 flowers from each of three species of iris: Iris setosa, versicolor, and virginica. You can get more details upon running ?iris.

The geometric attribute used to produce histograms is defined simply by specifying geom="histogram" in the qplot function. This default histogram will represent the variable specified in the function on the x axis, while the y axis will represent the number of elements in each bin. One other very useful way of representing distributions is to look at the kernel density function, which represents an approximation of the distribution of the data as a continuous function instead of different bins, by estimating the probability density...

Bar charts


Bar charts are usually used to explore how one (or more) categorical variables are distributed. In qplot(), this is done using the geom option bar. This geometry counts the number of occurrences of each factor variable, which appears in the data. To show an example of the bar chart, we will use the movies dataset, which is included within the ggplot2 package. We have already seen how to recall the dataset included with the basic installation of R, but if you are interested in the list of datasets within a specific package (ggplot2 in this case), you can use the following code:

require(ggplot2)       ## Load ggplot2 if needed
data(package="ggplot2")  ## List of dataset within ggplot2

The movies dataset contains information about movies, including the rating, from the http://imdb.com/ website. You can get a more detailed description in the help page of the dataset.

This dataset contains different variables but, for our example, we will not need all of them, so let´s rearrange a bit...

Boxplots


Box plots, also known as box-and-whisker plots, are a type of plot used to depict a distribution by representing its quartile values. In such plots, the upper and lower sides of the box represent the twenty-fifth and seventy-fifth percentiles (also called the first and third quartiles), while the horizontal line within the box represents the median of the data. The difference between the first and third quartiles is defined as Inter-Quartile Range (IQR), and it is often used as a measure of statistical dispersion of a distribution. The upper whisker represents the higher values up to 1.5*IQR of the upper quartile, while the lower whisker represents lower values within 1.5*IQR of the lower quartile. The pieces of data not in the whisker range are plotted as points and are defined as outliers. You can get additional details and references in the package website shown at the end of the chapter.

In this section, we will see some examples of boxplots using the dataset created in the previous...

Left arrow icon Right arrow icon

Description

This book is perfect for R programmers who are interested in learning to use ggplot2 for data visualization, from the basics up to using more advanced applications, such as faceting and grouping. Since this book will not cover the basics of R commands and objects, you should have a basic understanding of the R language.

Who is this book for?

This book is perfect for R programmers who are interested in learning to use ggplot2 for data visualization, from the basics up to using more advanced applications, such as faceting and grouping. Since this book will not cover the basics of R commands and objects, you should have a basic understanding of the R language.

What you will learn

  • Familiarize yourself with some important data visualization packages in R such as graphics, lattice, and ggplot2
  • Realize different kinds of simple plots with the basic qplot function
  • Understand the basics of the grammar of graphics, the data visualization approach implemented in ggplot2
  • Master the ggplot2 package in realizing complex and more advanced graphs
  • Personalize the graphical details and learn the aesthetics of plotting graphs
  • Save and export your plots in different formats
  • Include maps in ggplot graphs, overlay data on maps, and learn how to realize complex matrix scatterplots

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 25, 2015
Length: 234 pages
Edition : 1st
Language : English
ISBN-13 : 9781785287558
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jun 25, 2015
Length: 234 pages
Edition : 1st
Language : English
ISBN-13 : 9781785287558
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 90.97
Learning Shiny
€32.99
RStudio for R Statistical Computing Cookbook
€36.99
ggplot2 Essentials
€20.99
Total 90.97 Stars icon
Banner background image

Table of Contents

8 Chapters
1. Graphics in R Chevron down icon Chevron up icon
2. Getting Started Chevron down icon Chevron up icon
3. The Layers and Grammar of Graphics Chevron down icon Chevron up icon
4. Advanced Plotting Techniques Chevron down icon Chevron up icon
5. Controlling Plot Details Chevron down icon Chevron up icon
6. Plot Output Chevron down icon Chevron up icon
7. Special Applications of ggplot2 Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8
(5 Ratings)
5 star 40%
4 star 40%
3 star 0%
2 star 0%
1 star 20%
L. G. Feb 27, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
THIS IS A COMPACT BOOK TO LEAR HOW TO MAKE GRAPHICS, IT DOES NOT SHOW ALL ADVANCED POSSIBILITY, BUT IS IS A GOOD INTRODUCTION FOR WHO IS STARTING FROM A BASIC MEDIUM LEVEL
Amazon Verified review Amazon
Graham Webster Jan 04, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Books published by Packt Publishing are a mixed bag in terms of quality; however this book on ggplot2 is pretty good. I have purchased a few books on ggplot2, and I consider it the best introduction available for a user who is familiar with R. The book has a clearly written and logical approach to the subject, and has a good balance between theory and practice. I think I now have a reasonable understanding of how the "grammar of graphics" works, and can understand the logic of the program. Other books tend to adopt a cookbook approach (and Winston Chang's R Graphics Cookbook is a good example of that ). A graphics program that is based on a grammatical approach deserves to be explained in a way that allows the reader to build on their knowledge in a systematic way and to be able to extend the given examples to other situations. I'll go back to Hadley's book on ggplot2 ; I might understand it better now !
Amazon Verified review Amazon
Luca Antonelli Aug 23, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Spiega le basi dei grafici in R, senza entrare in dettagli complicati, o grafici molto complessi, ma concentrandosi sulla "filosofia" del pacchetto. Manca una parte sull'utilizzo del pacchetto all'interno di funzioni definite dall'utente.
Amazon Verified review Amazon
Dimitri Shvorob May 14, 2016
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I am going to be less diplomatic than Graham Webster and say that 90% of Packt output is garbage - and I keep checking out their titles purely for the other 10%. "ggplot2 Essentials" is among those positive surprises. OK, it is not a five-star book. First, specific editorial choices have made presentation less effective, and wasted space, reducing "core" page count to 100+. (To mention a specific peeve - the geom list on pages 97-101 was a disappointment: I would have liked illustrations, not simply a list). Second - and this is not the author's fault - Packt's standard no-frills black-and-white looks are a material problem for a book about a graphics package; the visually appealing books by Wickham and Chang surely "sell" "ggplot2" better. On the other hand, I see a competently written, substantial, non-copycat book which absolutely delivers the "ggplot2 essentials" it has promised in the title, and makes an effort to explain that advertised "grammar of graphics". Agreeing with Graham Webster again, the latter element was lacking in Winston Chang's otherwise proficiently crafted book. Still, Chang's has other strengths. My recommendation to a "ggplot2" novice would be the "Chang's plus Teutonico's" combo.UPD. On second thought, my recommendation to a "ggplot2" novice would be: drop R and switch to Python. It even has a ggplot port.
Amazon Verified review Amazon
Michael Fahey Dec 29, 2017
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Hey PACKT publishing. The next time you want to write book on graphics and visualization PRINT IT IN COLOR!!!!! The world moved away from black and white monitors about 25 years ago. This is absolutely the most bizarre thing I have seen in my life where an author probably wrote a great book describing how to build color visualizations in ggplot2 and a cheap two bit lamebrain publisher decided to save 10 cents by printing it in black and white. What a waste of paper and money and time.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.