<jupyter_start><jupyter_text>DS104 Data Wrangling and Visualization : Lesson Four Companion Notebook  Table of Contents * [Table of Contents](DS104L4_toc)    * [Page 1 - Introduction](DS104L4_page_1)    * [Page 2 - Histograms](DS104L4_page_2)    * [Page 3 - Histograms in Python](DS104L4_page_3)    * [Page 4 - Bar Charts](DS104L4_page_4)    * [Page 5 - Bar Charts in R](DS104L4_page_5)    * [Page 6 - Bar Charts in Python](DS104L4_page_6)    * [Page 7 - Stacked Bar Charts](DS104L4_page_7)    * [Page 8 - Stacked Bar Charts in R and Python](DS104L4_page_8)    * [Page 9 - The Pareto Principle](DS104L4_page_9)    * [Page 10 - Scatter Plots](DS104L4_page_10)    * [Page 11 - Scatter Plots in Python](DS104L4_page_11)    * [Page 12 - Line Charts](DS104L4_page_12)    * [Page 13 - Line Charts with Multiple Dependent Variables](DS104L4_page_13)    * [Page 14 - Line Charts in R](DS104L4_page_14)    * [Page 15 - Line Charts in Python](DS104L4_page_15)    * [Page 16 - Area Charts](DS104L4_page_16)    * [Page 17 - Google Trends](DS104L4_page_17)    * [Page 18 - Key Terms ](DS104L4_page_18)    * [Page 19 - Lesson 4 Hands-On](DS104L4_page_19)      Page 1 - Introduction[Back to Top](DS104L4_toc)<jupyter_code>from IPython.display import VimeoVideo
# Tutorial Video Name: Histogram and Bar Charts
VimeoVideo('241240235', width=720, height=480)<jupyter_output><empty_output><jupyter_text>IntroductionUsually the first thing people want to do with a set of data is get a feel for the distribution of those data. Whether the data are quantitative or categorical, there is a way to visualize the most important findings.In this lesson, you will learn how to create: * Histograms* Bar charts* Stacked bar charts* Scatter plots* Line chartsYou will also learn about the concepts behind: * Pareto plots* Area charts* Google TrendsThis lesson will culminate in a hands on in which you will create several different charts in the language of your choice.            Additional Info!                You may want to watch this  recorded live workshop that goes over the Python material  in this lesson or this  recorded live workshop on the R material in this lesson. .<jupyter_code>from IPython.display import VimeoVideo
# Tutorial Video Name: Histogram and Bar Charts
VimeoVideo('432027835', width=720, height=480)
from IPython.display import VimeoVideo
# Tutorial Video Name: Histogram and Bar Charts
VimeoVideo('438414531', width=720, height=480)<jupyter_output><empty_output><jupyter_text>Page 2 - Histograms[Back to Top](DS104L4_toc)  HistogramsA histogram is a graphical representation of the distribution of quantitative data. It was first introduced by <NAME>. To construct a histogram, the first step is to "bin" the range of values — that is, divide the entire range of values into a series of intervals — and then count how many values fall into each interval.The bins are usually specified as consecutive, non-overlapping intervals of a variable. The bins must be adjacent, and are usually of equal size. A typical simple histogram looks like this:![A histogram of monthly salary. The x-axis represents gross monthly salary and the y-axis represents frequency. The x-axis ranges from 800 dollars to 1800 dollars in 11 units. The y-axis ranges from 0 to 200 in five units.](Media/L03-01.png)The horizontal axis shows the range of values for the quantitative variable that is being displayed. The vertical axis tracks the counts for each value in each bin. ---  Page 3 - Histograms in Python[Back to Top](DS104L4_toc)  Histograms in PythonSince you have already learned how to create a histogram in R, you will now go over how to create them in Python. You will be using **[data from a human resources department](https://repo.exeterlms.com/documents/V2/DataScience/Data-Wrang-Visual/HR_data.zip)**. --- Histograms with PandasThe easiest way to create a histogram in Python is to use the ```pandas``` package, with the function ```.hist()```.  All you need to do is specify the dataset name, then the variable name and the function ```.hist()```: ```pythonHR.satisfaction_level.hist()```And here is the result: ![A bar chart represents 0 to 1.0 with six units on the x-axis and 0 to 2000 with 8 units on the y-axis.](Media/quant1.png)You may encounter a situation where the histogram doesn't populate, only text somewhat like this: ```text```If that happens, don't panic! All that is required is to re-run the cell again, and you'll be good to go.--- Single Histogram with SeabornThe next way to make histograms is to use a package called ```seaborn```.  You will need to import it with this import statement: ```pythonimport seaborn as sns```Then you can use the function ```displot``` out of seaborn to initiate an automated histogram with a best-fit curved line: ```pythonsns.distplot(HR['satisfaction_level'])```And here is the result: ![A graph depicts the satisfaction level. The x-axis ranges from 0 to 1.0 in six units and the y-axis ranges from 0 to 2.00 in 8 units.](Media/quant2.png)            Caution!                You will get an error if you try to run seaborn plots with missing data!    --- Multiple Histograms with SeabornWhat if you wanted to see histograms for all your quantitative data at once? Well, then you can make use of the ```seaborn``` function ```pairplot()```, run on the entire ```HR``` dataset: ```pythonsns.pairplot(HR)```And here's what you'll receive in return for that little snippet of code! The histograms are shown on the middle diagonal.![Sixty-four graphs depicting the plot of satisfaction level, last evaluation, number project, average monthly hours, time spend company, work accident, left, and promoters list five years.](Media/quant3.png)--- Histograms with MatplotlibWhile the histogram options in ```pandas``` and ```seaborn```are quick and easy to use, they lack the ability to customize the graphs with titles, labels, colors, and other parameters.  For that, you will need the holy grail of data visualization in Python: the package ```matplotlib```. Start by importing it and it's related subpackages: ```pythonimport matplotlib.mlab as mlabimport matplotlib.pyplot as plt```Then you can start to get funky! You can create a variable for the number of bins you'd like in your histogram, like this: ```pythonnum_bins = 5```Then specify the details of the plot. You basically will call the function ```plt.hist()```, then specify your variable, make a call to your bins variable, ```num_bins```, and then you can specify the argument of ```facecolor=``` to the color you'd like and specify the argument ```alpha=```. ```pythonn, bins, patches = plt.hist(HR['satisfaction_level'], num_bins, facecolor='blue', alpha=.05)```Then you will call this plot with the function ```.show()```:```pythonplt.show()```These three snippets of code can all go in the same Jupyter Notebook cell and be run together.  When you do so, here is the result: ![A graph in which the x-axis ranges from 0 to 1.0 in six units and the y-axis ranges from 500 to 4000 in eight units. The plot shows a stairs-like structure.](Media/quant4.png)The ```alpha=``` argument is for adjusting the color transparency - if you leave it at .05, you get the pretty washed out colors that you see above.  But if you change it to something higher, like 2, you get a much deeper color, like below: ![A graph in which the x-axis ranges from 0 to 1.0 in six units and the y-axis ranges from 500 to 4000 in eight units. The plot shows a stairs-like structure.](Media/quant5.png)--- Adding Labels and a TitleIf you want to add labels to any of your ```matplotlib``` graphs, you can do so like this: ```pythonplt.xlabel('Satisfaction Level')plt.ylabel('Frequency')```Where you are using the function ```xlabel()``` for labeling the x-axis, and you are using the function ```ylabel()``` for labeling the y-axis.  Just specify the text you'd like inside of the parentheses and quotes.If you'd like to add a title to the graph, you can do so with the function ```title()```, which functions the same way as the labels - just place your text in the parens and quotes: ```pythonplt.title('Histogram of Satisfaction Level')```When you combine it all together, your code might look something like this for the whole enchilada: ```pythonnum_bins = 5n, bins, patches = plt.hist(HR['satisfaction_level'], num_bins, facecolor='blue', alpha=.05)plt.xlabel('Satisfaction Level')plt.ylabel('Frequency')plt.title('Histogram of Satisfaction Level')plt.show()```And here is what the graph would look like: ![A histogram of satisfaction level. The x-axis represents the satisfaction level and it ranges from 0 to 1.0 in five units and the y-axis represents the frequency that ranges from 0 to 4000 in eight units.](Media/quant6.png)---  Page 4 - Bar Charts[Back to Top](DS104L4_toc)  Bar ChartsAt a glance, a bar chart looks a lot like a histogram. But when you get into the details, there is one huge difference between bar charts and histograms: > A histogram is a visualization of a quantitative variable, whereas a bar chart is a visualization of a categorical variable.Bar charts can be represented either vertically, like this: ![A bar chart depicts the grades of students. The x-axis represents four bars labeled A, B, C, and D and the y-axis represents students and it ranges from 0 to 15 in four equal intervals. The first bar reaches four on the y-axis, the second bar reaches 12 units on the y-axis, the third bar reaches 10 units on the y-axis, and the fourth bar reaches 2 units on the y-axis.](Media/L03-05.png)The bar chart above shows student grades. The horizontal axis lists the grades received, and the vertical axis shows a count of students earning that particular grade. Bar charts can also be represented horizontally, like this:  ![A bar chart with four units on the x-axis and three units on the y-axis. The x-axis ranges from 0 to 20. The y-axis has three units labeled giraffes, orangutans, and monkeys. The bar for monkeys crosses 20 units on the x-axis. The bar for orangutans about to reach 15 units on the x-axis and the bar for giraffes reaches 20 units on the x-axis.](Media/L03-06.png)The height (or length) of each individual bar is a representation of how many units are in that category.--- Ordering Bars How do you know what order to put the categories in? There are no rules, but several options: * **Logical progression:** You can order them according to some sort of logical progression. For example, the student grades graph shown above is ordered logically, from A to D.* **Height*** **Time:** If a bar graph of death tolls from several wars was created, it would make sense to order them in time order of when the war took place.* **Alphabetically:** Lots of software programs will default to ordering the categories alphabetically, which may or may not make any sense. --- Multiple Categorical VariablesBar charts are also great at showing differences between groups.  Now, instead of a single categorical variable being tracked, you are tracking two different categorical variables in the bar chart. This is often called a *grouped bar chart*. Check out this bar chart:![A bar chart depicts the sales of chocolate, vanilla, and strawberry flavors for Harpo, Chico, and Groucho. The sales of chocolate flavor for Chico is high, Groucho is low, and Harpo is average. The sales of Vanilla flavor for Harpo is high, Chico is medium, and Groucho is low. The sales of strawberry flavor for Chico is high, Groucho is medium, and Harpo is low.](Media/L03-07.png)As you can see, the two categorical variables are ```flavor``` and ```Marx brother```. The vertical axis shows the sales for each of these products, and by person. This type of bar chart enhances the ability to perform eyeball analysis, because you can quickly and easily compare between flavors, brothers, and the interaction between flavor and brother.  ---   Page 5 - Bar Charts in R[Back to Top](DS104L4_toc)  Bar Charts in RThere are many ways to create bar charts in R, with a wide variety of packages available for plotting.  However, you will learn two systems: one building on your ```ggplot``` knowledge, and one using the ```lattice``` library.--- Bar Charts with ggplotYou can add the ```geom_bar()``` function to your ```ggplot()``` function to make a bar chart, like this: ```{r}ggplot(HR_data, aes(salary))+   geom_bar() +  ggtitle("Frequency of Salary") +  xlab("Salary Category") +  ylab("Frequency")```And here is the result: ![A bar chart depicts the frequency of salary. The x-axis represents the salary category as high, low, and medium. The y-axis represents the frequency from 0 to 6000 in four units. The biggest bar is the category low, the second biggest bar is the category medium, and the smallest bar is the category high.](Media/quant7.png)--- Bar Charts with LatticeYou can also install and work with a library called ```lattice``` for plotting in R.  It is  quick and easy way to plot. All you really need to do is to specify your variable, using the function ```barchart()```:```{r}barchart(HR_data$salary)```And here is the resulting graph below.  Notice that by default the bar chart is horizontal, not vertical. ![A bar chart depicts the frequency of salary. The y-axis represents the salary category as high, low, and medium. The x-axis represents the frequency from 0 to 6000 in four units. The biggest bar is the category low, the second biggest bar is the category medium, and the smallest bar is the category high.](Media/quant9.png)A word of caution - your variable must be a factor in order to use the ```barchart()``` function from ```lattice```.  If you use a variable in a different format, even if it represents categorical data, things will come up pretty screwy.  Take a look at what happens when you chart ```Work_accident```, which is a categorical variable, but currently structured as numeric: ```{r}barchart(HR_data$Work_accident)```![A graph depicts the HR data work accident. The x-axis has five units and it ranges from 0.0 to 1.0. A rectangular bar plotted till it reaches point 1.0 on the x-axis. The bar is divided at the point X equals 0.0.](Media/quant8.png)Quite confusing and nonsensical. --- Adding Labels and a TitleNow, if you want to pretty up your ```lattice``` chart, you can add some arguments to it to do so.  ```main=``` will provide a title, ```ylab=``` will allow you to label the y-axis, and ```xlab=``` will allow you to label the x-axis.  You can also add in a ```color=``` argument to change the color from the default glaring blue. Maybe you'd prefer neon green instead?```{r}barchart(HR_data$salary, main="Frequency of Salary", ylab = "Salary Category", xlab = "Frequency", col="green")```![A bar chart depicts the frequency of salary. The y-axis represents the salary category as high, low, and medium. The x-axis represents the frequency from 0 to 6000 in four units. The biggest bar is the category low, the second biggest bar is the category medium, and the smallest bar is the category high.](Media/quant10.png)---  Page 6 - Bar Charts in Python[Back to Top](DS104L4_toc)  Bar Charts in PythonThere are a few different ways to make bar charts in Python as well.  The easiest way is probably to use ```pandas```, however. Call the variable you want, then use the function ```.value_counts()```, and call on top of it the function ```plot()```, specifying that you want it to be a ```'bar'``` chart as an argument. Altogether, it should look like this:  ```pythonHR['salary'].value_counts().plot('bar')```And here is what it will end up looking like:![A bar chart depicts the frequency of salary. The x-axis represents the salary category as low, medium, and high. The y-axis represents the frequency from 0 to 7000 in seven units. The biggest bar is the category low, the second biggest bar is the category medium, and the smallest bar is the category high.](Media/quant11.png)--- Adding Labels and a TitleTo add labels and a title, you will first need to give your graph a name, so that you can call the functions on your graph.  You will call your graph ```SalaryFreq```. ```pythonSalaryFreq = HR['salary'].value_counts().plot('bar')SalaryFreq.set_title("Salary Frequency")SalaryFreq.set_xlabel("Salary Categories")SalaryFreq.set_ylabel("Frequency")```And then you can use the functions ```set_title()``` to add a title to your graph, ```set_xlabel()``` to add a label for the x-axis, and ```set_ylabel()``` to add a label for the y-axis.Now the result is a beautifully labeled graph. ![A bar chart depicts the frequency of salary. The x-axis represents the salary category as low, medium, and high. The y-axis represents the frequency from 0 to 7000 in seven units. The biggest bar is the category low, the second biggest bar is the category medium, and the smallest bar is the category high.](Media/quant12.png)---  Page 7 - Stacked Bar Charts[Back to Top](DS104L4_toc)  Stacked Bar ChartsOne other variety of bar chart that is useful to compare two different categorical variables at the same time is called a *stacked bar chart*. A stacked bar chart looks like this:![A bar chart depicts the number of referrals in March, April, and May for four persons. The y-axis represents the number of referrals and the x-axis represents Bob, Alice, Tony, and Cathy. Each bar has three subdivisions represent March, April, and May. The bar for Bob reaches 45 on the y-axis. The bar is divided in such a way that the month May takes the majority of the portion, then, April, and then March. The bar for Alice reaches 45 on the y-axis. The bar is divided in such a way that the month May and March have almost equal portions. The bar for Tony reaches 35 on the y-axis. The bar is divided in such a way that three divisions are almost equal. The bar for Cathy reaches 40 units on the y-axis. The bar is divided in such a way that referrals in March are a little higher than in April.](Media/quant13.jpg)Two categorical variables are being measured.  The first is the person, which is labeled along the x-axis, and the second is the Month, which is color-coded and has a key in the upper left. The frequencies, in number of referrals, is shown on the y-axis. One caution about using a stacked bar graph is this: For all colors except for the bottom color (March, in this example), it can be challenging to determine which bar is higher, because the bottom of each colored section is often at different places vertically.For example, look at ```April``` for ```Bob``` and ```Tony```. Can you tell for sure which is taller? It's hard to say, because they both start at different points on the graph. Stacked bar charts may rob you of the ability to compare between bars for a certain group. Sure, you could include a table of values, or put the values into the colored portions of the bars themselves. But the whole point of visualization is to enhance interpretation. If you cannot interpret the findings without explicitly including the data, have you really gained anything?---  Page 8 - Stacked Bar Charts in R[Back to Top](DS104L4_toc)  Stacked Bar Charts in RStacked bar charts are easy to create in R using ```ggplot```. Simply add a ```mapping=``` argument to your ```geom_bar()``` function that allows you to specify your ```x=``` variable and the variable that you will be stacking, which goes in the argument ```fill=```. Here's what that code will look like:```{r}ggplot(data=HR_data) +  geom_bar(mapping = aes(x = sales, fill=salary)) +   ggtitle("Sales Categories by Salary Level") +  xlab("Sales Category") +  ylab("Frequency") ```Which will then produce this graphic: ![A bar chart depicts the plot of sales category by salary level. The x-axis represents the salary category. The salary categories are labeled accounting, hr, IT, management, marketing, product mng, Rand D, sales, support, and technical. The y-axis represents the frequency. Each bar has three divisions represent high, medium, and low. The frequency for the category sales is the highest. The frequency for the category management is the lowest.](Media/quant14.png)--- Making Bar Heights the SameOne of the difficulties with stacked bar charts is the ease of interpretation - it's hard to do when the bars are all varying heights! But if you are able to set the bar heights the same, interpretation becomes much easier! Simply add another argument to ```geom_bar()``` called ```position=``` and set it to ```"fill"```: ```{r}ggplot(data=HR_data) +  geom_bar(mapping = aes(x = sales, fill=salary), position = "fill") +   ggtitle("Sales Categories by Salary Level") +  xlab("Sales Category") +  ylab("Frequency")  ```Now you can see that it is much easier to compare the amount in each colored bar! ![A bar chart depicts the plot of sales category by salary level. The x-axis represents the salary category. The salary categories are labeled accounting, hr, IT, management, marketing, product mng, Rand D, sales, support, and technical. The y-axis represents the frequency. Each bar has three divisions represent high, medium, and low and all the bars reach 1.00 on the y-axis.](Media/quant15.png)--- Multiple Categorical VariablesWhen you do a stacked bar chart, you are including two categorical variables.  However, one is stacked! You can also compare them side by side if you'd rather.  That's also an easy fix in ```ggplot```: just change the ```postion=``` argument to ```"dodge"```, which will place your bars side by side.  If you have the room, this is one of the best ways to compare the differences between categories. Here is the code: ```{r}ggplot(data=HR_data) +  geom_bar(mapping = aes(x = sales, fill=salary), position = "dodge") +   ggtitle("Sales Categories by Salary Level") +  xlab("Sales Category") +  ylab("Frequency")  ```And it will produce a plot that looks like this: ![A bar chart depicts the plot of sales category by salary level. The x-axis represents the salary category. The salary categories are labeled accounting, hr, IT, management, marketing, product mng, Rand D, sales, support, and technical. The y-axis represents the frequency. Each category has three bars represent high, medium, and low and all the bars reach 1.00 on the y-axis.](Media/quant16.png) Stacked Bar Charts in PythonStack bar charts are easy to create with ```pandas```! You create a data frame with ```pd.crosstab``` to create a cross table of two categorical variables, then add ```plot.bar(stacked=True)``` to the data frame variable like so:```{r}crosstab_df = pd.crosstab(HR_data['sales'], HR_data['salary'])crosstab_df.plot.bar(stacked=True)```Which will produce an image like the one below.![Stacked Bar Chart in Python](Media/StackedBCiPy.png "Stacked Bar Chart in Python")            Additional Info!                If you would like to make stacked bar charts with matplotlib and seaborn, please visit this site.    ---  Page 9 - The Pareto Principle[Back to Top](DS104L4_toc)  The Pareto PrincipleV<NAME> was an Italian engineer and philosopher who lived in the late 19th and early 20th century. He is credited with crating the *80/20* rule, which also came to be known as the *Pareto principle*.The Pareto principle was built on the observation that about 80% of the land in Italy at the time was owned by about 20% of the landowners. It turned out that this sort of breakdown applies to all sorts of natural phenomena. Pareto also noticed that in his garden, 20% of the peapods contained 80% of the peas.            Fun Fact!                The Pareto principle is sometimes called 'the law of the vital few,' or the 'principle of factor sparsity.'    --- Applications of the Pareto PrincipleThe Pareto principle has applications in the following areas:* **Business management:** 80% of sales come from 20% of clients* **Economics:** 80% of the wealth is controlled by 20% of the population* **Software:** Microsoft noted that fixing the 20% most common bugs would fix 80% of the errors and crashes* **Sports training:** roughly 20% of the exercises and habits have 80% of the impact on a trainee* **Occupational Health:** 20% of the hazards account for 80% of the injuries* **Health care:** 20% of the patients use 80% of the resources* **Crime:** 80% of all crimes are committed by 20% of criminals--- The Pareto ChartAs with a bar chart, a pareto chart is set up so that the vertical axis is the frequency of occurrence for most pareto charts, but it can also be some sort of quantitative measure, such as cost or another important unit of measure.Pareto charts are one of the 'seven basic tools of quality.' They are especially useful in problem solving. Here is an example:![A Pareto chart of late arrivals by reported cause. The x-axis represents traffic, child care, public transportation, weather, overslept, and emergency. The left side of the chart ranges from 0 to 60 with 10 unit intervals and the right side of the chart ranges from 0-percent to 100-percent. The bars are arranged in decreasing order and a curve drawn in an increasing pattern.](Media/quant17.png)This pareto chart is a list of causes for late arrival, listed along the horizontal axis. The vertical axis shows the count of defects for each type. One other feature of pareto charts is that they have a cumulative percentage axis (usually on the right), and a line trend that shows the cumulative amount of total defects, starting from the left.So, if you wanted to decrease the number of late arrivals to your company, then you could take a peek at the heavy hitting categories of ```Traffic```, ```Child Care```, and ```Public Transportation```, and brainstorm how you could impact those factors.  For instance, perhaps if you staggered employee start times a little later in the day, rush hour traffic could be avoided, and most likely employees would be happier as well! ---  Page 10 - Scatter Plots[Back to Top](DS104L4_toc)<jupyter_code>from IPython.display import VimeoVideo
# Tutorial Video Name: Scatterplots
VimeoVideo('241240275', width=720, height=480)<jupyter_output><empty_output><jupyter_text>Scatter PlotsHave you ever been curious about how two quantitative variables interact? A graphical way to represent two quantitative variables and their interaction is a *scatterplot*. A scatter plot (also called a scatter graph, scatter chart, scattergram, or scatter diagram) is a type of plot used to display values for two continuous variables for a set of data. The data are displayed as a collection of points, with the value of one variable determining the position on the horizontal axis, and the value of the other variable determining the position on the vertical axis.![A graph depicts the plot of height against weight. The unit of height is represented in meters and the unit of weight is represented in kilograms. Fifteen points are plotted on the graph in an increasing pattern.](Media/quant18.png)This graph is a basic scatterplot, where two quantitative variables are being plotted against each other. In this case, the horizontal variable, or x, is ```Height```, and the vertical variable, or y, is ```Weight```. Each dot on the scatterplot represents a single person, and by drawing an imaginary line straight down and straight to the left from each data point will tell you the height and weight of a person.--- Using Color in Scatter PlotsThere are lots of great options with scatterplots. Using colors or symbols or both, you can create scatterplots that have multiple groups on them, which can be really useful in telling a story. Here is an example:![A graph depicts the plot of sepal length against the sepal width. The x-axis represents the sepal length and the y-axis represents the sepal width. The x-axis ranges from 0 to 7.8 and the y-axis ranges from 2 to 4.4. The points are plotted for three categories labeled Iris-setosa, Iris-versicolor, and Iris-virginica.](Media/L05-21.png)This is a scatterplot where two quantitative variables _and_ a categorical variable are demonstrated on the same graph. --- Scatterplot MatricesYou also didn't cover a scatterplot matrix. There may be a time when you have more than two quantitative variables in your dataset, and you want to do all possible combinations of two variables. Scatterplot matrices will give you graphs that look like this: ![Ten graphs are placed in four rows. The first row has four graphs and they are labeled Sepal.length, R equals minus 0.12, R equals 0.87, and R equals 0.82. The second row has three graphs and they are labeled Sepal.width, R equals minus 0.43, R equals minus 0.37. The third row has two graphs and they are labeled Petal.Length, R equals 0.96. The last row has one graph labeled Petal.width.](Media/L05-22.png)Note that there are four different quantitative variables in the data set, so there are six possible combinations of those four variables, hence six scatterplots.   Page 11 - Scatter Plots in Python[Back to Top](DS104L4_toc)  Scatter Plots in PythonSince you have previously learned how to create scatter plots in R, you'll now learn how to do scatter plots in Python! You will use the [USDA Nutrition Dataset](https://repo.exeterlms.com/documents/V2/DataScience/Data-Wrang-Visual/USDA_nutrition.zip), which lists the nutritional content for a lot of different foods.The simplest way to make scatterplots in Python is to use ```pandas```.  A simple scatter plot can be created by specifying the data frame now, and then calling the ```.plot.scatter()``` function, and specifying an ```x=``` and ```y=``` variable as arguments: ```pythonPlot = nutrition.plot.scatter(x='fats', y='sat fats')Plot.set_title("Fats by Saturated Fats")Plot.set_xlabel("Fats")Plot.set_ylabel("Saturated Fats")```And here is the resulting plot: ![A graph depicts the plot of fats by saturated fats. The x-axis represents fats and the y-axis represents saturated fats. The x-axis ranges from 0 to 100 with five equal unit intervals and the y-axis ranges from 0 to 80 with four-unit intervals.](Media/quant19.png)--- Scatter Plots with a Third Quantitative VariableYou can add a third quantitative variable to your scatter plot if you are feeling wild and crazy! It can be added as either a size or color component.  Here's the most simple color component, which can be created by adding as an argument ```c=```: ```pythonPlot = nutrition.plot.scatter(x='fats', y='sat fats', c='protein')Plot.set_title("Fats by Saturated Fats and Protein")Plot.set_xlabel("Fats")Plot.set_ylabel("Saturated Fats")```You'll get a graph that is in greyscale, and the depth of the grey indicates the amount of protein in the data points: ![A graph depicts the plot of fats by saturated fats and protein. The y-axis represents saturated fats and it ranges from 0 to 80 with four-unit intervals. The points plotted are in different shades. A color scale with different shades is placed on the right side of the figure. The color bar is labeled protein. The scale ranges from 0 to 35.](Media/quant20.png)--- Adding ColorWant to add some pizzazz to that grey on black color scheme? Then you are in luck, because you can specify a color palette if you'd like, with the argument ```cmap=```. ```pythonPlot = nutrition.plot.scatter(x='fats', y='sat fats', c='protein', cmap='coolwarm')Plot.set_title("Fats by Saturated Fats and Protein")Plot.set_xlabel("Fats")Plot.set_ylabel("Saturated Fats")```Things may be a little clearer now on a blue to red color theme: ![A graph depicts the plot of fats by saturated fats and protein. The y-axis represents saturated fats and it ranges from 0 to 80 with four-unit intervals. The points plotted are in different shades. A color scale with different shades is placed on the right side of the figure. The color bar is labeled protein. The scale ranges from 0 to 35.](Media/quant21.png)--- By SizeYou can also display that third variable by size instead if you'd like, with the argument ```s=```. Here's what that would look like:```pythonPlot = nutrition.plot.scatter(x='fats', y='sat fats', s=nutrition['protein'])Plot.set_title("Fats by Saturated Fats and Protein")Plot.set_xlabel("Fats")Plot.set_ylabel("Saturated Fats")```And the graph it creates:![A graph depicts the plot of fats by saturated fats. The x-axis represents fats and the y-axis represents saturated fats. The x-axis ranges from 0 to 100 with five equal unit intervals and the y-axis ranges from 0 to 80 with four-unit intervals.](Media/quant22.png)If the dots are too small to read, you can always change the size by adding a multiplier. Just add ```*``` to the end and the number by which you want to multiply: ```pythonPlot = nutrition.plot.scatter(x='fats', y='sat fats', s=nutrition['protein']*2)Plot.set_title("Fats by Saturated Fats and Protein")Plot.set_xlabel("Fats")Plot.set_ylabel("Saturated Fats")```And the result is a little more readable: ![A graph depicts the plot of fats by saturated fats. The x-axis represents fats and the y-axis represents saturated fats. The x-axis ranges from 0 to 100 with five equal unit intervals and the y-axis ranges from 0 to 80 with four-unit intervals.](Media/quant23.png)---  Page 12 - Line Charts [Back to Top](DS104L4_toc)<jupyter_code>from IPython.display import VimeoVideo
# Tutorial Video Name: Line Charts
VimeoVideo('241241450', width=720, height=480)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.07776739136990019, 'fraction_numerical': 0.01764014112112897, 'mean_word_length': 4.61435584899272, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 20, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '339021', 'license': 'MIT', 'n_tokens_mistral': 9348, 'n_tokens_neox': 8489, 'n_words': 4920, 'path': 'Data Science and Machine Learning/Machine-Learning-In-Python-THOROUGH/RECAP_DS/03_DATA_WRANGLING_AND_VISUALISATION/L04.ipynb', 'repo_name': 'okara83/Becoming-a-Data-Scientist', 'size': '33177'}