1. Home
  2. Explore
  3. Statistics
  4. Data Visualization with R

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Data Visualization with R

Transcript

hello everyone and welcome to data science dojos live tutorial on introductory data visualization with our and ggplot2 my name is Blair Huckle and I am the marketing manager here at data science dojo and I will be moderating today's webinar before we begin the webinar I would like to mention that all lines will be muted for the duration of the webinar but questions are encouraged to ask a question use the questions module on the right side of your screen moving on to today's agenda I will provide a brief introduction to our speaker today Dave Langer they will then jump right into the presentation including the use of our code we will save time at the end of the webinar to answer questions in the event that we do not have enough time to answer all questions feel free to post any questions that you have on the meetup comm page for this webinar and Dave will be happy to answer them we ask that you please participate as this will allow us to bring you other interesting

tutorials in the data science field lastly if you are interested in following along with the presentation both the slides and our code are available via github at the URL you see here the URL is also available via the meetup comm page for this webinar our presenter today is Dave Langer vice president of data science at data science dojo dave has trained hundreds of working professionals via data science dojos unique five day bootcamp format and has trained thousands more via his YouTube tutorials prior to joining data science dojo Dave worked at Microsoft where he led a Technical Program management team accountable for all the data systems used to run Microsoft's ten billion dollar supply chain operations they've joined data science dojo to realize the company's mission of data science for everyone it is Davis belief that you do not need a PhD in statistics or machine learning to learn data science and apply it to your daily work to derive business

value dave has experience across numerous analytical technologies and techniques but his current focus areas are text analytics event log mining and mathematical programming Dave's true passion however is teaching others data science feel free to connect with Dave via LinkedIn YouTube and Twitter if he can be of help in your data science journey Dave welcome to this data science dojo webinar thank you Blair that introduction it's a pleasure to be here today to talk to everyone about ggplot2 a subject that I am particularly excited about and something I teach all of our students about in our data science dojo boot camps okay before we get started let's talk a little bit about expectation setting I like to do this with each of my meetups or each of my webinars or each of my tutorials just so that you know what to expect from the time that you invest in this presentation so first up I'm going to assume the following I'm going to assume that you are experienced with our coding

I'm not going to say that you're an expert but I'm going to assume that you can hack that you can understand our code when you see it because we don't have a lot of time at our disposal so we're going to focus mainly on how to work with ggplot2 and not so much about our syntax next up I'm going to assume that you have some data visualization knowledge for example what is a histogram or what is a box and whisker plot we're not going to talk a little not going to talk about the actual visualizations of themselves we're going to focus more on how to use ggplot2 to create those visualizations lastly and probably most importantly I'm going to assume that you're interested in how you can use ggplot2 to accelerate and improve your data visualizations in your day to day work as a data professional so out of necessity because this is a limited time that we have together oh this is just going to be a quick intro to visualization which is you plot to so

they're a consequence I'm going to have to gloss over a lot of things for example in ggplot2 you can actually create very rich layered visualizations with actually multiple layers of things going on all at the same time unfortunately this is an advanced topic and we won't have time to talk about it today but we will have time to talk about is the twenty twenty percent of ggplot2 that is useful eighty percent of the time we're going to use the 8020 rule here to talk about ggplot2 and focus on the kinds of visualizations and the kinds of questions that you want to answer using ggplot2 if you get interested in ggplot2 and I hope that you will I will provide resources later in the deck for you to learn more more in-depth resources to get better would you plot to Dancer all kinds of different types business questions that you may have overall my goal though is to make you excited about ggplot2 I'm a big fan of ggplot2 I use it every day in my work I teach it in every

single one of our boot camps to our students at data science dojo it is a wildly wildly useful tool as a data professional as a data scientist okay so as Blair mentioned I used to work at Microsoft before coming to data science dojo and I spent a number of years as a program manager so I've learned to look at the world in terms of scenarios and personas and this presentation will be no different we'll use a scenario to create a frame of reference for understanding the data that we're looking at why we're looking at the data the kinds of business questions that we can formulate over that data and the visualizations that we use to help us answer those questions but before we dive into the scenario we need to talk a little bit about the prerequisites if you wish to follow along either during this presentation or after the fact you're going to need the following you're going to need our and you are going to need our studio now strictly speaking our studio is optional

you absolutely have to have the our programming language of course but our studio is an optional add-on I would highly recommend that use our studio I will be doing the entire demo in our studio and I always recommend to folks that they use our studio because it does make your our coding experience a lot more productive and a lot more enjoyable next up of course you're also going to need the ggplot2 package installed in your environment all the code that we will be using today is going to be leveraging ggplot2 so you absolutely have to have that package installed and lastly as Blair mentioned earlier the github repository for this webinar has the source file it has the data file and it also has the PDF of all view slides okay so talk a little bit about the data so the first question you may ask is why use this data set and the data set in question that we use is the tango competitions Titanic machine learning from disaster data set now if you've seen any of our data science dojo

meetups or presentations or webinars you know that we use this data set extensively and we do the for two primary reasons one everyone is familiar with the proper domain I've literally asked this question to hundreds of people essentially I say how many of you are not familiar with the Titanic what happened on the Titanic puts it the story of the Titanic raise your hands and universally nobody raises their hand so everyone's familiar with the problem domain and this is important

because when we do these tutorials we do these webinars where do these meetups we have lots and lots of different folks with lots of different backgrounds from different industries so on and so forth so using a particular data set for a particular problem domain can be problematic with that diverse of an audience but everyone is familiar with what happened on the Titanic so it's part of the reason why we use it it's super important next up believe it or not the actual Titanic data set that you can get from kaggle is actually a good proxy for a common business data for example it is a good proxy for customer profile data that is the kinds of things that you see in the Titanic data set the nature of the data the fact that it's not 100% clean the fact that it has overloaded data columns in terms of meaning is actually highly representative of the kinds of things that you see in the business world for example if you were going to pull customer profile data for example to

build a predictive predictive model for understanding whether or not a customers are going to churn going to leave your company to go to a competitor you would go to your data warehouse you go to your data Mart you pull the cusp your customer profile data a lot of the characteristics in that data match what you see in the Titanic data set so it is extremely useful for precisely that reason so to illustrate that we can go over the data dictionary for the Titanic data set and what you can see here is the data dictionary and down this list of column this column here we have all the variables all the columns in the data frame that are available in the Titanic data so first up we have a variable called survived and it defines survival essentially it's a binary indicator it's zero when a passenger in the Titanic did not make it that they perished and it's a one if they actually survived next up we have the ticket class or pee

class now the way to think about this in modern times is trains you can buy a first-class ticket on a train a second-class ticket on a train or a third-class ticket on a train all of these all these these are designations of the level of accommodations that you have on the train in a similar fashion on the Titanic you also have first-class tickets set glass tickets third-class ticket stead to find your accommodation on the boat next up we have an indicator of gender the sex variable it's going to be male or female we also have a variable in the data set for age this is a continuous variable it's a numeric column it has decimal points in it so for example you'll see ages of you know thirty three point four four years that sort of thing and the next step we have two variables called sub spawn parch and the reason why these are interesting is because what I mentioned on the previous slide which is oftentimes in well-established

business systems that you would work with as an analyst or data scientist certain data fields get overloaded in database terms certain columns on tables get overloaded over time people say hey I want to add a new aspect of my business process but I don't have the time to actually go through and modify the computer systems or the databases hey there's this this there's this data this data value over here I can overload it so sometimes it means this and sometimes it means that happens all the time in modern business systems and this is what we actually have here in this SIP spa and parch variables the first one is overloaded it is the count of the number of siblings and or whether or not you're traveling with a spouse notice how it's overloaded it can either be just the number of brothers and sisters that you're traveling with or it could be your spouse or I could be the combination of siblings and your spouse that you're traveling with next up we have parch similarly parked is

overloaded is the count of the number of parents or the number of children that you'll be traveling with aboard the Titanic again notice how it's overloaded into war and/or so these two are very indicative of the kinds of things that you see in the real world next up we have ticket which is just the serial number of your ticket on the Titanic we have fare how much you paid for your ticket in pound sterling next up we have cabin not every not every passenger the Titanic actually had a cabin number but if you did have a cabin number assigned to you you would be listed here and then lastly there's a column that denotes where you got on the ship your port of embarkation see for Cherbourg q for queenstown and s for southampton and the reason why we're going through this data is to level-set everybody on the webinar today about the data set because this is going to be super important because understanding these columns and what

they mean are critical for actually saying I have this type of business question I would like to create a visualization that potentially answers that question so you know what pieces of data to use in that visualization okay so now familiar with the data set we can talk about our scenario so we are a consulting data scientist this is our hypothetical scenario so we're a consulting data scientist and we've been hired by a company to analyze the Titanic data set let's say it's the The Star Line company that actually ran the ran the actual shipping line okay in particular the goal of our analysis is to explain patterns of survival in the data the business folks that have hired us as the consultant wants to know hey who survived and who died and why explain to me the patterns in the data that determines survival and here's the thing to note and this is super important the audience is decidedly non data savvy and this is actually very common well this is a contrived scenario

in fact the scenario has very very many real world analogs it's very common for consultants to be hired not to be necessary familiar with the problem domain and try to create an understanding of what's going on in the data and explain it to an audience that may not so it'll be data savvy so there's many analogs in the real world customer churn fraud detection if you're an e-commerce site under saying conversion rates all those sorts of things mimic this scenario and also mimic what we'll see in our analysis of the data and the tools and techniques that we use like ggplot2 the visualizations that we use to actually understand what's going on in the data now here's the critical thing because our audience is decidedly non data savvy we probably shouldn't lead the presentation of our findings with things like summary statistics or any sort of complicated mathematical representations of the data ideally what we should be using is intuitive visualizations that

leverage the power of the human brain to do pattern recognition visually to allow us to tell our story in a much more intuitive fashion so using the power of ggplot2 we will do precisely this as we walk through the our code okay so that's our scenario that's what we're doing that's what we're trying to achieve let's now start talking a little bit about ggplot2 okay if you fire up our studio and you type in a command into R say look show me the help file for the

ggplot2 package this is what you'll see this is what you'll see create elegant data visualizations using the grammar of graphics not surprisingly the grammar of graphics rgg is where the Gigi and Gigi plot to comes from now ggplot2 has become the de facto standard visualization tool in our and to illustrate the point you are probably like me you probably have various social media feeds whether that's Twitter or LinkedIn or Facebook and if you're interested in data science topics you'll

get a feed of LinkedIn posts and articles or articles on Facebook or tweets what have you all regarding data science and usually what they'll have is in the feed is a graphic to go along with the teaser text to get you to click on it if you're interested invariably at least once a day and often many times a day I see visualizations and those grit in those graphics in that feed that are obviously coming from ggplot2 and that the reason I bring that up is it shows you how ubiquitous ggplot

- is in the data science community are is pretty ubiquitous and people who use are tend to also use ggplot2 so this is a this is a very very valuable tool for you to have in your tool belt as a data professional using arm now the reason why arguably it's become the de facto standard is because ggplot2 was designed from the ground up to allow you as an AR coder to create print quality graphics literally in seconds it takes very very few keystrokes in R to actually produce

a high-quality graphics suitable for printing in a magazine or an academic journal or anything else that you can think of and in particular what also makes UT plot to extremely extremely important and extremely well extremely widely used in R is not only the fact that it makes you productive you can create these visualizations in seconds but if you need to you can exhibit very fine-grained control very fine-grained control specifically there is a collection of functions an API or

application programming interface the ggplot2 provides that manifests the grammar and what this allows you to do is to write your R code using the ggplot2 library in such a way that you essentially have fine-grained custom control over the way the images look by layering on various aspects of this visual grammar to eventually result in this graphic that you would like to have and this is super powerful now the thing I need a caution though is that the next slide in particular you may think oh man ggplot2 is extremely complicated I see fine grained control Dave's talking about finder and controlled madness be a really steep learning curve involved in ggplot2 no that's not true ggplot2 is both both complicated with fine grained control allows you to do many many things that you would like exactly the way you would like and it's also easy to use it literally will allow you to create print quality graphics in seconds now I know

those two things seem to be at odds but bear with me over the next couple of slides and I'll explain further ok the grammar so every visualization in ggplot2 is posed of the following things this is this is the six aspects of the ggplot2 grammar and graphics okay first up you have the data which is the raw material for your visualization makes total sense you absolutely have to have data no data no visualization next up the other aspect of the grammar is what is known

as layers and the easiest way to think about layers is this is what you actually see in your visualization these are things like the points the lines the bars the whatever whatever is on whatever is on your graphic whatever is in your visualization these are the layers that's what you see but in order to actually render those layers correctly you need a scale because as you might imagine if you have a column of data and you have a hundred thousand values and they while and they wildly

vary in terms of the individual values in each one of the in the cells in your column you only have so much real estate on the screen on the computer screen so you need something to scale the data down to map the data to the graphical output so that it makes sense so the scale is the part of the grammar that actually shrinks or manipulate your data in such a way that it will fit consistently and intelligently on the limited screen rules say that you have on your computer that's the way to think about scales next up you have coordinates the coordinates are the visualizations perspective so for example the default coordinate system that you use is a two dimensional grid an XY plane everyone's familiar with this right every time you create a bar chart or a line chart or histogram your honor grid this is the one used by default and the vast majority of the time it's the one you're going to use but it's not the only coordinate system then you could potentially use and

ggplot supports multiple coordinates but in general you tend to use the default which is a grid next up in the grammar you have faceting in the easiest way to think about faceting is that it provides visual drill down into the data and the easiest way to think about this is if you're familiar with Excel you can use what are known as pivot tables in Excel and they allow you to drill down in your data and once you get down to a certain level of granularity right you've drilled down by this variable and that variable by this category in that category so on and so forth you get a collection of data and then in Excel 2016 you can actually ask it to create a pivot chart a visualization based on that drill down so you focus on a certain subset of the data based on your grille down and Excel will create for you a chart based on that drill down very useful this is what you use faceting for this is GG plots way of mimicking what Excel does with

pivot charts so it's very very useful very very powerful as we'll see in a bit and then lastly we have themes themes allows you to do fine allows you to have fine-grained control over certain details of the display for example fonts both font am I using what's the size of the font what's the color schemes that I'm using that sort of thing things are extremely useful for customizing your visualizations to be to have a look and feel that you desire so those are the three aspects of the grammar now here's the kicker here's the kicker this seems super complicated I'm sure some of you are saying scales and coordinates and faceting Dave what's going on I don't I just want to drop I just want to draw a chart why do I need into all this well the good news is generally speaking working with a grammar you actually don't need to know all of that to get started and the reason for that is most of the time the defaults work well for

you out-of-the-box you only need to get to that level of detail if you want to create a more customized graphic if you want to tweak something just so to get just the look that you're interested in you have that power but most of the time you're probably not going to be interested in that and it's okay ggplot2 will work without you having to drill down to that level of detail so let's talk about what you actually need in practice 20% of the time excuse me what you need to work with the grammar of graphics 80% of the time is you know a small subset so let's talk about what you absolutely have to have to get a ggplot2 graphic going in your environment it's not surprising the first thing that you need is the data okay hopefully enough said next up you need in a spec and anesthetic essentially is a mapping of your data to the visualization for example let's say you're creating a plot a chart and you would like the y-axis to

essentially be mapped to the ages of the Titanic passengers in your data set so the y-axis is age and the x-axis is something else you can actually do that directly in our code using the ggplot2 API in fact you have to do it because you ggplot2 needs to know how you want the data mapped now once again if I use Excel as an analogy this will be this should be intuitive to you because for example let's say you're in Excel and you have a worksheet and on this worksheet you have

some data so you select some cells that have some data in them in your worksheet and you say you know what Excel please create for me a chart now depending on the nature of the chart that you pick and the nature of the data you select Excel automatically maps those cells to either the y-axis or the x-axis depending on the data in the nature of the chart that you pick you don't have to do it yourself but you know that that's what's going to happen and in fact once the chart is created you can obviously double click on it and actually alter the mappings say look you know what know what I don't want the x-axis to be this these cells anymore I want to actually be the data in these cells now same idea a lot of times in Excel it automatically does the aesthetic mapping for you can ggplot2 you still do it you still have to do it of course because it's required you just have to write a little bit of code to make it happen and we'll see examples of that later and then lastly the only

other thing that you need to create a ggplot2 visualization is a layer which makes sense if if you don't tell ggplot that you want dots or lines or bars it doesn't know what to actually display so you have to provide a layer so these these layers these graphics that you that you have ggplot render for you take the function in our code as G Amagi on functions so literally in package there are dozens of functions that all start with the prefix GE om which is sort for geometry geometry on

underscore bar GM underscore histogram these functions actually define the visualization that you will actually want to do plot to to render based on the data that you provide and the aesthetic mappings that you define so this is actually pretty simple as well see this is actually very little code to actually required to get a nice visualization going and we'll see that just a second in the art code okay as promised here the resource here's the resource that I was mentioning about

ggplot2 so the book ggplot2 by Hadley Wickham is the single best resource for learning ggplot2 hands down because quite frankly happy Wickham wrote ggplot2 he created he's the creator of the package so who better to teach you ggplot2 than the man himself mr. Wickham another reason why I love this book is because it is a great resource for folks of all levels of skill and experience and so in my particular case let me use myself as an example by the time I bought this book I

actually had quite a bit of experience with ggplot2 I've been using it for a number of years but most of my experience was just based on trial and error I learned ggplot2 by hacking it I googled things when I ran into problems I you stackoverflow etc so by the time I bought the book I actually knew quite a bit about ggplot2 but I still learned a lot by reading it and what's even better yet is that even if you're inexperienced actually even if you have absolutely no experience in ggplot2 you're an absolute beginner with ggplot2 the book is not too advanced it taught me things even though I've been using ggplot2 for a number of years and it can teach folks with no experience in ggplot2 it's great for both types of folks so I absolutely positively recommend it if you're only going to buy one resource on ggplot2 this is the book this is the book to buy okay excellent so enough with slides let's go ahead and actually take a look at the our code now

okay so what I've got here is an our studio environment and I have the code file which you can get from the github I've already set up my our studio environment to point it's working directory where I downloaded the Titanic data from the github repository for this webinar so it's pointing to the right place on my local hard drive here to actually read in the data so if you do not have ggplot2 you can highlight this code right here and run it and that would install ggplot2 or we'll reach across the internet to a repository grab the ggplot2 binary pull it down installed in your local environment I already have ggplot2 installed so I'll just go ahead and load it first thing because that's what we need to complete this particular video and assuming this particular webinar and these lines of code that I have highlighted here will actually load up the CSV data frame load up the CSV into a data frame and then it'll actually show us the Titanic data in our

Studios spreadsheet view using this view function so let's go ahead and do that okay so first things that we'll notice is that the status that's not particularly large it's only 891 observations of 12 columns of data but as I indicated before despite its small size there's actually a lot of goodness packed into this data set which is why we use it a data science dojo extensively not only in our meetups and our webinars but we also use it in our bootcamp as well because there's a lot of a lot of good teaching that you can get out of this data set ok so a couple things that I want to point out first and foremost is that we have two columns here name and passenger ID which we did not see in the data dictionary in the PowerPoint slides so the reason for that is quite frankly is they're not particularly useful you'll notice here the passenger ID is essentially a unique identifier it's basically starts at one and it increases by one for each row and

the data it's just a unique identifier if you're familiar with databases this is essentially the primary key of passengers and it's not going to be useful because each individual passenger has a unique ID so from an analytical perspective there's not any signal there next up we have name like passenger ID if you take a look at all the names there are 891 unique names no names are duplicated in this data set so from an analytical perspective the names in their current form aren't very useful

there's no there's no analytical signal in this data now you might imagine that if we decided to use some regular expressions or some text analytics on this data we could probably get some signal out of it and that's absolutely true however that's beyond the scope of today's webinar so as a consequence we're just going to ignore passenger ID and we're going to ignore name so next up the second thing that I want to wanted to show you in the state of in this data set is the importance of recognizing the categorical variables and making sure that we assign those variables explicitly to be categories and let me use survived in P class of the primary examples so as we know from the data dictionary slide survive is a binary indicator it is zero if the passenger perished and it's one if they survived but by default when we read this data in from the CSV our R is going to interpret survived as being a numeric column because as far as its concerned it's a bunch of integer values but we

know as the data professional has the data scientist that in fact survived shouldn't be a numeric column because it's actually not going to be using any sort of mathematical context for example we would never do multiplication and division on the survived column it makes no sense to divide values and survived by themselves or multiply them together or anything like that we wouldn't do math like that ergo survived really isn't what is known as ratio data it's not really numeric

we're not going to use a Furnham sort of numeric calculations so that's our new negation to us that it should probably be a factor it should be a categorical variable either you survived or you didn't essentially in a similar fashion we can analyze p class so p class has three very three values one two and three and again we can apply our heuristic of saying would we do multiplication or division on p-class data and the answer is no it doesn't make any sense to do that third

class cannot be interpreted P class of three cannot be interpreted as being three times a P class of one not really that doesn't make a lot of sense reflexively you cannot think of a P class of one as being one third of the P class of three it doesn't make sense this is not ratio data therefore it also makes sense for p class to also be a factor to be a category in our terms lastly we should also be looking at our sex column as being a factor obviously because it's string data and there's

only two values male and female those are the categories and we also have embarked notice that we have our string our individual character data here of SC and Q these are distinct values you're either either on the ship in Southampton or sure board or Queenstown so we should probably make this a factor as well well I'm in here one quick thing I should also point out notice in the age column we're missing data we're missing data in the age column here that's going to be important later ggplot2 will accommodate this and we should take a look at it just so that we're aware of what ggplot does in the situation will we try to create graphics visualizations on columns where some data is missing okay so there's our data so obviously next up we're going to go ahead and set all of these variables that should be factors as factors so I'm just going to run run this code and good to go now the reason why this is important is because ggplot2 is smart ggplot2 is

smart in certain aspects of how you code up visualizations of ggplot2 if you provided factor variables as part of the visualization as part of the aesthetic as part of the mapping he will do cool and interesting things as we'll see in a bit we can actually use factor variables to actually color code our visualizations and really make them pop in terms of the information that they can portray okay cool so we've got our data prepped and we're good to go so going back to our Center we're a consulting data scientist we've been hired by a company to analyze the Titanic data and understand the underlying signal in the data explained to me based on the data the story of who survives and who doesn't in the Titanic okay cool so not surprisingly since maybe we're not super familiar with the Titanic data set and we're consulting data scientists the first thing we may want to know is in general what was the survival rate we this is the first time

we look at the data we should probably actually understand what is survival rates so we can do that pretty easily with just this small amount of code now notice how this mimics the last slide that we talked about in the deck the last slide about ggplot2 specifically that we talked about in the deck that you only need three things first up you need your data please ggplot2 work with the Titanic data next up we need anesthetic and in particular we're saying a ggplot2 map

the x-axis to the survived column of the titanic data set and then lastly we need a layer and here we're saying please use GM underscore bar which actually translates in ggplot2 to a bar chart a bar chart is an excellent thing to use for categorical data because essentially a bar chart is just a count and since categorical data can't be thought of in terms of more advanced mathematical operations like multiplication and division basically the only thing you can do is talk about factoring

categorical variables in terms of accounts okay as always let's go ahead and use the help system here so first up let's do a quick help find it on the ggplot function itself and notice here that it says okay did you plot to create a new GG plot excellent that makes a lot of sense to us good next up we can look up the AES function so let's do question mark AES and enter and you can see here construct aesthetic mappings so all that makes a lot of sense how we can interpret this code is this is the

foundation GG plot I want to start building a new visualization here's the data I want you to use here's the aesthetic mapping map the x-axis to the survived column of the Titanic data frame and then lastly layer on a bar chart and as I mentioned before we can type in down here in the command line if we're going to type in under GM underscore notice how many entries we get look at all of these functions all of these functions many many functions we can do a violin plot we can put in

text we can do ribbons and we can do polygons we do histograms all kinds of things many many visualizations are possible and they all start with G on and when you see GM underscore you know that you're talking about a very specific type of visualization a very specific type of chart or plot so this is a bar chart okay so it's highlight these two lines of code and run them and I'll clear out this code down here because we don't need it anymore and I'll zoom in and take a look at this

very easily we have a print quality graphic print quality visualization and you'll notice that along the x-axis we have survived zero for those folks that perished on the Titanic and a one for those people that survived and notice right away we can tell that more people perished and survived unfortunately on the Titanic and we can also kind of estimate you know relative proportions here as well so we have about 550 people out of 891 perished and about 340 let's

say people or so that survived and we just look at this from this chart now a question that I get is get asked often is Dave what if I actually want to place on these on these charts the actual percentages just because I don't want to eyeball it I actually just want to know what the percentages are you can absolutely do that unfortunately the the code that you need is a little bit more advanced than we have time to talk about in this particular video but regardless what I advise people do when they're first starting ggplot2 and they want to know about relative percentages don't bother putting them on the plots per se at least to start with just use this type of our syntax here prop table feed into it the results of the table command and if I run this highlighted line of code I get the relative percentages about 62% of the passengers unfortunately perished on the Titanic and about 38% survived and if you go back here and look at the

graphic yeah you can roughly kind of eyeball and say yeah that seems seems about right except out right okay so moving on so this so this is this graphic is is is print quality but it's probably not customized enough to actually print so let's add a little bit of ggplot2 code actually improve this a little bit so one of the things we're going to do is we're going to improve this label notice how it's just count we're going to change this to make it something a

little more intuitive and notice that the title there's no title for this plot so we'll actually add a title for this plot so notice that the first thing that I can do is I can just copy this code and then paste it and then add some add some items to it that's exactly what I did and this is a cornerstone of an hour developer and our programmers productivity zing ggplot2 there's a lot of what is known as copy and paste reuse because notice that this line of code

right here is exactly the same as this line of code right here notice that this line of code right here is exactly the same as this line of code right here so I copy and pasted it and I just added some stuff the stuff that I added was a theme which we'll talk about in a second and I added a call to the labs function and as always using the help system question mark labs modify the axis legend and plot labels so this is a function that I can use to change the label on the y-axis and this is a function that I can use to set the title of my plot now getting back to the theme you'll notice here that the default background that you get in ggplot2 is this gray this is the default background that you for me personally I don't like the gray just my own personal opinion I like a nice clean background I like it to be white so this theme actually defines a white background instead of a gray background so I like to use it so that's what I commonly have in my GG plots so

if I highlight all this code and I run it you can now see our modified visualization and notice here that we get a nice passenger count label here on the y-axis we get a new title called Titanic survival rates and a nice white background so this is actually a print quality graphic you could actually submit this to for example an academic journal for publication very easy very quick and easy to do alright moving on so for the consulting data scientist we have an understanding

of the relative proportion of survival now between those who survived those didn't so the next question we can ask ourselves is well what's a working hypothesis for this data if you're familiar familiar with the nautical space there is a popular adage that essentially says women & children first so being relatively new to the space let's say is this is this consulting data scientist we assume hey that's a reasonable hypothesis to explore can actually ggplot2 to answer the question

what was the survival rate by gender and that's actually relatively easy notice that once again I can take this copy and paste reuse from the previous visualization and just modify it a little bit for it to work now to answer this question and the two things that I needed to change to answer this question well technically the three things I need to change our first of all I map the x-axis now to sex instead of it being survived as it was in the previous plot I now map the x-axis to sex and then I add something called fill and I mention this earlier if you provide fill as part of your aesthetic mapping to ggplot2 and you assign to it a categorical variable what you get is a nice color coding many many of the genomes of the layers in ggplot2 have the ability to be filled to be color coded with a fill rate and what this does essentially is says look each of my bars will now be filled based on a value the value have survived

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent