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

Arrow left icon
Profile Icon Donato Teutonico
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8 (5 Ratings)
Paperback Jun 2015 234 pages 1st Edition
eBook
€10.99 €16.99
Paperback
€20.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Donato Teutonico
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8 (5 Ratings)
Paperback Jun 2015 234 pages 1st Edition
eBook
€10.99 €16.99
Paperback
€20.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€10.99 €16.99
Paperback
€20.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. €18.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781785283529
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. €18.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jun 25, 2015
Length: 234 pages
Edition : 1st
Language : English
ISBN-13 : 9781785283529
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
ggplot2 Essentials
€20.99
RStudio for R Statistical Computing Cookbook
€36.99
Learning Shiny
€32.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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.