Book Image

R Data Visualization Recipes

By : Vitor Bianchi Lanzetta
Book Image

R Data Visualization Recipes

By: Vitor Bianchi Lanzetta

Overview of this book

R is an open source language for data analysis and graphics that allows users to load various packages for effective and better data interpretation. Its popularity has soared in recent years because of its powerful capabilities when it comes to turning different kinds of data into intuitive visualization solutions. This book is an update to our earlier R data visualization cookbook with 100 percent fresh content and covering all the cutting edge R data visualization tools. This book is packed with practical recipes, designed to provide you with all the guidance needed to get to grips with data visualization using R. It starts off with the basics of ggplot2, ggvis, and plotly visualization packages, along with an introduction to creating maps and customizing them, before progressively taking you through various ggplot2 extensions, such as ggforce, ggrepel, and gganimate. Using real-world datasets, you will analyze and visualize your data as histograms, bar graphs, and scatterplots, and customize your plots with various themes and coloring options. The book also covers advanced visualization aspects such as creating interactive dashboards using Shiny By the end of the book, you will be equipped with key techniques to create impressive data visualizations with professional efficiency and precision.
Table of Contents (19 chapters)
Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Creating simple stacked bar graphs


Stacked bars are often settled to display how data is distributed across categories with respect to other categories. Using ggplot2, stacked bar plots can be simply handled by geom_bar() function; that would require nothing more than explicitly declaring the fill parameter. To demonstrate how ggplot2, ggvis and plotly can craft simple stacked bar plots we shall use car::Salaries data frame.

Getting ready

The data frame is Salaries from the car package. We also need the plyr package:

> if( !require(car)){ install.packages('car')}
> if( !require(plyr)){ install.packages('plyr')}

Make sure to have the internet connection before running above code.

How to do it...

After looking at the data, ggplot2 can deploy stacked bars by naming the fill argument:

  1. Call the geom_bar() function to make sure to have the bar geometry:
> library(ggplot2)
> gg2_sal <- ggplot( data = car::Salaries, aes(x = rank))
> gg2_sal + geom_bar(aes(fill = sex))

Check the following...