Data visualization with R and ggplot2 | the R Graph Gallery (2024)


Data visualization with R and ggplot2 | the R Graph Gallery (1)

ggplot2 is a R package dedicated to data visualization. It can greatly improve the quality and aesthetics of your graphics, and will make you much more efficient in creating them.

ggplot2 allows to build almost any type of chart. The R graph

gallery focuses on it so almost every section there starts with ggplot2 examples.

This page is dedicated to general ggplot2 tips that you can apply to any chart, like customizing a title, adding annotation, or using faceting.

If you love ggplot2, you will love my productive r workflow project where I show how it interacts with Quarto, Git and Github! ❤️

A world of geom

ggplot2 builds charts through layers using geom_ functions. Here is a list of the different available geoms. Click one to see an example using it.

geom_bar geom_bin geom_boxplot geom_density geom_error geom_hex geom_hist geom_hline geom_jitter geom_label geom_line geom_point geom_polygon geom_rect geom_ribbon geom_rug geom_segment geom_smooth geom_text geom_tile geom_violin geom_vline

Annotation with ggplot2

Annotation is a key step in data visualization. It allows to highlight the main message of the chart, turning a messy figure in an insightful medium. ggplot2 offers many function for this purpose, allowing to add all sorts of text and shapes.

Annotate with geom_text geom_text() allows to add annotation to one, several or all markers of your chart.
Annotate with geom_label Very close to geom_text, geom_label produces a label wrapped in a rectangle. This example also explains how to apply labels to a selection of markers.
Rectangle Learn how to use the annotate function to add a rectangle on a specific part of the chart.
Segment How to add one or several segments to the chart.
Arrow Basically the same as for a segment, with just one additional argument.
Abline Add horizontal or vertical ablines with geom_hline and geom_vline.
Curved arrows Dicover how to draw curved arrows in ggplot

Marginal plot

Marginal plots are not natively supported by ggplot2, but their realisation is straightforward thanks to the ggExtra library as illustrated in graph #277.

Scatterplot with rug Add rug on X and Y axis to describe the numeric variable distribution. Show how geom_rug() works.
Marginal distribution Add marginal distribution around your scatterplot with ggExtra and the ggMarginal function.
Marginal boxplot Using boxplots is another way to show the marginal distribution. Find more in this post.

ggplot2 chart appearance

The theme() function of ggplot2 allows to customize the chart appearance. It controls 3 main types of components:

  • Axis: controls the title, label, line and ticks
  • Background: controls the background color and the major and minor grid lines
  • Legend: controls position, text, symbols and more.
Axis Customize ggplot2 axis: title, line, labels and ticks.
Background Customize ggplot2 background: color, major and minor grid lines.
Legend Customize ggplot2 legend: position, title, text, key symbol and more.

Re-ordering with ggplot2


When working with categorical variables (= factors), a common struggle is to manage the order of entities on the plot.

Post #267 is dedicated to reordering. It describes 3 different way to arrange groups in a ggplot2 chart:

  • Using the forcats package
  • With dplyr
  • With the reorder() function of base R

Read post

ggplot2 title

The ggtitle() function allows to add a title to the chart. The following post will guide you through its usage, showing how to control title main features: position, font, color, text and more.

Basic Learn how to add a title with ggtitle, default options.
Appearance Learn how to change title font, size, color, text and more.
Position Check how to change title position.

Use custom fonts with ggplot2

If you don't want your plot to look like any others, you'll definitely be interested in using custom fonts for your title and labels! This is totally possible thanks to 2 main packages: ragg and showtext. The blog-post below should help you using any font in minutes.

Custom font Learn how to add a custom font using the ragg or the showtext library in a ggplot2 chart.

Small multiples: facet_wrap() and facet_grid()

Small multiples is a very powerful dataviz technique. It split the chart window in many small similar charts: each represents a specific group of a categorical variable. The following post describes the main use cases using facet_wrap() and facet_grid() and should get you started quickly.

Facet_wrap Facet wrap allows to build small multiples using one categorical variable.
Facet_grid Same idea, but using 2 categorical variables for the faceting.
Customized An advanced examples to make sure you know how to make your small multiple pretty.
Strip features Customize the general layout with the strip option.
Mixing charts How to combine several charts together with ggplot2.

A set of pre-built themes

It is possible to customize any part of a ggplot2 chart thanks to the theme() function. Fortunately, heaps of pre-built themes are available, allowing to get a good style with one more line of code only. Here is a glimpse of the available themes. See code


→ ggplot2

default theme_bw() theme_minimal() theme_classic() theme_gray()

→ ggthemes

theme_excel() theme_economist() theme_fivethirtyeight() theme_tufte() theme_gdocs() theme_wsj() theme_calc() theme_hc()

→ other

theme_article() theme_pubclean() theme_bigstatsr() theme_ipsum()

Data visualization with R and ggplot2 | the R Graph Gallery (25)Data visualization with R and ggplot2 | the R Graph Gallery (26)

plotly: turn your ggplot interactive

Another awesome feature of ggplot2 is its link with the plotly library. If you know how to make a ggplot2 chart, you are 10 seconds away to rendering an interactive version. Just call the ggplotly() function, and you’re done. Visit the interactive graphic section of the gallery for more.

library(ggplot2)library(plotly)library(gapminder)p <- gapminder %>% filter(year==1977) %>% ggplot( aes(gdpPercap, lifeExp, size = pop, color=continent)) + geom_point() + theme_bw()ggplotly(p)

this chart is interactive: hover, drag, zoom, export and more.

An overview of ggplot2 possibilities

Each section of the gallery provides several examples implemented with ggplot2. Here is an overview of my favorite examples:

Violin + boxplot + sample size This examples provides 2 tricks: one to add a boxplot into the violin, the other to add sample size of each group on the X axis
Add individual observation See how low group C sample size actually is?
Map marker feature to variable Ggplot2 makes it a breeze to map a variable to a marker feature. Here is an example where marker color depends on its category.
Improve appearance Make your chart pretty with nice color scale, general theme, stroke around cirle and more..
Custom appearance Classic appearance customization with theme_ipsum and more
Improve general appearance Add title, use a theme, change color palette, control variable orders and more
Conditional color Change shape parameters depending on where the data points is located compared to a threshold.
Cleveland dot plot A variation of the lollipop chart to study several categories on the same chart.
Customization Add scale, group names and more
Customization Usual customizations like title, theme, color palette and more.

Data art

Sometimes programming can be used to generate figures that are aestetically pleasing, but don't bring any insight. Here are a few pieces of data art built from R and ggplot2. Visit data-to-art.com for more.

Droid A BB8 droid made using R and ggplot2.
Random Shapes A piece of generative art built with R and ggplot2.
R Snail R Snail, a generative figure made by Christophe Cariou, built with R.

Related chart types

Ggplot2

Animation

Interactivity

3D

Data visualization with R and ggplot2 | the R Graph Gallery (45)

Caveats

Data visualization with R and ggplot2 | the R Graph Gallery (46)

Data art

Data visualization with R and ggplot2 | the R Graph Gallery (2024)

References

Top Articles
What Gives Bread Flavor?
3.4 Puzzle Time Answers
Spasa Parish
Rentals for rent in Maastricht
159R Bus Schedule Pdf
Sallisaw Bin Store
Black Adam Showtimes Near Maya Cinemas Delano
Espn Transfer Portal Basketball
Pollen Levels Richmond
11 Best Sites Like The Chive For Funny Pictures and Memes
Things to do in Wichita Falls on weekends 12-15 September
Craigslist Pets Huntsville Alabama
Maine Coon Craigslist
‘An affront to the memories of British sailors’: the lies that sank Hollywood’s sub thriller U-571
Tyreek Hill admits some regrets but calls for officer who restrained him to be fired | CNN
Haverhill, MA Obituaries | Driscoll Funeral Home and Cremation Service
Rogers Breece Obituaries
Ems Isd Skyward Family Access
Elektrische Arbeit W (Kilowattstunden kWh Strompreis Berechnen Berechnung)
Omni Id Portal Waconia
Kellifans.com
Banned in NYC: Airbnb One Year Later
Four-Legged Friday: Meet Tuscaloosa's Adoptable All-Stars Cub & Pickle
Model Center Jasmin
Ice Dodo Unblocked 76
Is Slatt Offensive
Labcorp Locations Near Me
Storm Prediction Center Convective Outlook
Experience the Convenience of Po Box 790010 St Louis Mo
Fungal Symbiote Terraria
modelo julia - PLAYBOARD
Abby's Caribbean Cafe
Joanna Gaines Reveals Who Bought the 'Fixer Upper' Lake House and Her Favorite Features of the Milestone Project
Tri-State Dog Racing Results
Navy Qrs Supervisor Answers
Trade Chart Dave Richard
Lincoln Financial Field Section 110
Free Stuff Craigslist Roanoke Va
Stellaris Resolution
Wi Dept Of Regulation & Licensing
Pick N Pull Near Me [Locator Map + Guide + FAQ]
Crystal Westbrooks Nipple
Ice Hockey Dboard
Über 60 Prozent Rabatt auf E-Bikes: Aldi reduziert sämtliche Pedelecs stark im Preis - nur noch für kurze Zeit
Wie blocke ich einen Bot aus Boardman/USA - sellerforum.de
Infinity Pool Showtimes Near Maya Cinemas Bakersfield
Hooda Math—Games, Features, and Benefits — Mashup Math
Dermpathdiagnostics Com Pay Invoice
How To Use Price Chopper Points At Quiktrip
Maria Butina Bikini
Busted Newspaper Zapata Tx
Latest Posts
Article information

Author: Velia Krajcik

Last Updated:

Views: 6267

Rating: 4.3 / 5 (54 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Velia Krajcik

Birthday: 1996-07-27

Address: 520 Balistreri Mount, South Armand, OR 60528

Phone: +466880739437

Job: Future Retail Associate

Hobby: Polo, Scouting, Worldbuilding, Cosplaying, Photography, Rowing, Nordic skating

Introduction: My name is Velia Krajcik, I am a handsome, clean, lucky, gleaming, magnificent, proud, glorious person who loves writing and wants to share my knowledge and understanding with you.