Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
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
€8.99 €16.99
Paperback
€20.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
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
Estimated delivery fee Deliver to Estonia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Estonia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

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
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

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela