ggplot2 is an R package specialized on data visualization. It is both a companion to the dplyr data manipulation package and a whole library by itself. Within a well defined framework, you can
easily draw a large number plot types with the same methodology
## If you have never installed ggplot2 before## install.packages("tidyverse")## First load the library## We will also use dplyr therefore tidyverse is betterlibrary(tidyverse)## We are going to use starwars datasets to show examplesstarwars
# A tibble: 87 × 14
name height mass hair_color skin_color eye_color birth_year sex gender
<chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr>
1 Luke Sk… 172 77 blond fair blue 19 male mascu…
2 C-3PO 167 75 <NA> gold yellow 112 none mascu…
3 R2-D2 96 32 <NA> white, bl… red 33 none mascu…
4 Darth V… 202 136 none white yellow 41.9 male mascu…
5 Leia Or… 150 49 brown light brown 19 fema… femin…
6 Owen La… 178 120 brown, gr… light blue 52 male mascu…
7 Beru Wh… 165 75 brown light blue 47 fema… femin…
8 R5-D4 97 32 <NA> white, red red NA none mascu…
9 Biggs D… 183 84 black light brown 24 male mascu…
10 Obi-Wan… 182 77 auburn, w… fair blue-gray 57 male mascu…
# ℹ 77 more rows
# ℹ 5 more variables: homeworld <chr>, species <chr>, films <list>,
# vehicles <list>, starships <list>
ggplot(starwars %>%select(name, species, height, mass) %>%filter(mass <1000) %>%filter(complete.cases(.)), aes(x = height, y = mass)) +geom_point(aes(color = species)) +labs(title ="Star Wars Characters by Height and Mass", subtitle ="Colors by species", x ="Height (in meters)", y ="Mass (in KG)", color ="Species") +theme_minimal() +theme(legend.position ="bottom")
Line plot geom_line
Let’s use another data for line plot, EUStockMarkets data from base R.
ggplot(stock_df_long,aes(x=date,y=close,color=symbol)) +geom_line() +labs(x="Date",y="Index Level at Close",title="Comparison of Stock Market Indices",subtitle="Period between 1991-1996",color="Index") +theme_dark()
Bar plot geom_bar
Back to starwars. Let’s see the frequency of “eye color” of characters and draw a bar plot.