<jupyter_start><jupyter_text>Introduction to matplotlib--- In this notebook, we will learn about the basics of matplotlib, yet another data science library.Estimated Time: 30 minutes---  1. Introduction*What is matplotlib?*Here's the Wikipedia definition: "matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy."Basically, matplotlib is a cool way we can create plots. A note on visualization in general: Visualization is SUPER important in data science. Sometimes, we create visualizations to examine our data before we begin analysis. Other times, we include visualizations in our final reports to convey important information in a nice manner.With that, let's learn about matplotlib! Let's import it as well as numpy to start us off!<jupyter_code>import numpy as np
import matplotlib.pyplot as plt<jupyter_output><empty_output><jupyter_text>--- 2. Basics of matplotlibFirst, let's talk about how matplotlib works in general. Here's how we do things: we work with the `plt` module (we imported matplotlib as `plt`, so that's the name we're going to use now), adding things to our plot one by one. Then, when we're done adding all of the things we want to add, we call `plt.show()` to display our plot with all of its features!Again, here's the general framework:`plt.  Adding things to our plot``plt.  Adding things to our plot``plt.  Adding things to our plot``plt.show()  When we're done`Now that we know that, let's go ahead and start doing fun stuff!---  3. Simple Line PlotLet's see how to create a line plot with matplotlib. What do you need to create a line? x and y coordinates of course! Let's make those:<jupyter_code>x = [1, 2, 3]
y = [4, 5, 6]<jupyter_output><empty_output><jupyter_text>To plot a line plot with these two arrays is easy! We need to call the plot function from plt, and pass in the x and y arrays. That's it!<jupyter_code>plt.plot(x, y)<jupyter_output><empty_output><jupyter_text>Huh? No plot's showing up! What did we forget..? Add in the line below!<jupyter_code>### YOUR CODE HERE
plt.show()<jupyter_output><empty_output><jupyter_text>Question 3.1:  Plot the x = y line by defining your own x and y arrays and then using matplotlib!<jupyter_code>### YOUR CODE HERE
x = [1, 2, 3]
y = [1, 2, 3]
plt.plot(x, y)
plt.show()<jupyter_output><empty_output><jupyter_text>--- 4. Bar ChartsWow, line plots sure were easy! Let's move on to more of a challenge: bar charts. To review, a bar chart consists of one or many bars. Each bar represents a different category of a categorical variable, and the height or y-value of each bar is the value of that category. For example, say we had the counts of the animals your friends owned. We could visualize this with a bar chart. In fact, let's do exactly that!<jupyter_code>animals = ["Cat", "Dog", "Bird", "Zebra"]
counts = [280, 120, 60, 3]<jupyter_output><empty_output><jupyter_text>We are going to use the `plt.bar` function. The required arguments are two things: 1) `left`, which is a sequence of scalars, which represents the x coordinates of the left sides of the bars2) `right`, which is also a sequence of scalars, which represents the heights of the barsThis may be a bit confusing, but here's what we're going to use for `left`: the array starting with numbers 0, 1, ..., up to the number of bars we want in our bar chart. We can accomplish with np.arange.As a reminder, np.arange(x) creates an array with numbers 0, 1, ..., x - 1, which is exactly what we want!<jupyter_code>left = np.arange(len(animals))<jupyter_output><empty_output><jupyter_text>Right would just be the counts, which we already have. Let's go ahead and plot our bar chart!<jupyter_code>plt.bar(left, counts)
plt.show()<jupyter_output><empty_output><jupyter_text>Hmm... this doesn't seem to be very informative. Our array for `left` placed our bars nicely, but we don't actually want those x-values there. We want labels which are our animals! Here's how we'll accomplish that:<jupyter_code>plt.bar(left, counts)
plt.xticks(left, animals)
plt.show()<jupyter_output><empty_output><jupyter_text>Basically, what we did was change our x-labels from the numbers to the labels for the animals with the function `xticks`. Question 4.1: Create your own bar chart! This time, we want you to plot the names of fruits against their counts. If you ever get stuck, feel free to look above, but try to do what you can from memory :)<jupyter_code>fruits = ["strawberry", "blueberry", "cantaloupe", "orange", "apple"]
fruit_counts = [100, 230, 3, 52, 64]
### YOUR CODE HERE
left = np.arange(len(fruits))
plt.bar(left, fruit_counts)
plt.xticks(left, fruits)
plt.show()<jupyter_output><empty_output><jupyter_text>--- 4. HistogramsThis is the final kind of plot we're going to learn today. Histograms! To review, histograms are "a diagram consisting of rectangles whose area is proportional to the frequency of a variable and whose width is equal to the class interval."Let's create a histogram of exam scores.<jupyter_code>scores = [80, 96, 78, 100, 23, 79, 93, 95]
plt.hist(scores)
plt.show()<jupyter_output><empty_output><jupyter_text>Wow, that was easy! Why don't you try?Question 4.1:  Create a histogram for these exam scores.<jupyter_code>other_scores = [83, 28, 12, 34, 29, 89]
### YOUR CODE HERE
plt.hist(other_scores)
plt.show()<jupyter_output><empty_output><jupyter_text>--- 5. CustomizationsWow, we've learned so many plots today! However you may notice... our plots are pretty basic. They have the main plot and that's it. Wouldn't it be nice to add in things like titles and x-labels and colors? Let's learn how to do that!Basically, we just need to add on more "layers" to our plot before calling show. Here are a few things we can add:a) `title`We can add a title to our plot by using `plt.title([name])`<jupyter_code>plt.plot(x, y)
plt.title("My Line Plot!")
plt.show()<jupyter_output><empty_output><jupyter_text>b) `xlabel`, `ylabel`We can add labels for our x and y axes with these functions.<jupyter_code>plt.plot(x, y)
plt.title("My Line Plot!")
plt.xlabel("cats")
plt.ylabel("dogs")
plt.show()<jupyter_output><empty_output><jupyter_text>c) Adding a splash of color!Let's figure out how to make our line a different color than what it is now! It's also pretty easy, we just need to add an extra thing to our plot call on plt.<jupyter_code>plt.plot(x, y, color='green') # We added color = 'green'
plt.title("My Line Plot!")
plt.xlabel("cats")
plt.ylabel("dogs")
plt.show()<jupyter_output><empty_output><jupyter_text>Question 5.1 Your turn! Go ahead and customize the barchart we created earlier. Make it look super nice!<jupyter_code>### ADD CUSTOMIZATIONS
plt.bar(left, counts)
plt.title("Animal Frequencies")
plt.xlabel("Animal Type")
plt.ylabel("Counts")
plt.xticks(left, animals)
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09700073152889539, 'fraction_numerical': 0.012289685442574982, 'mean_word_length': 5.225865209471767, 'pattern_counts': {'":': 0, '<': 65, '<?xml version=': 0, '>': 65, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '16', 'dir': 'jupyter-structured-clean-dedup', 'id': '366560', 'license': 'MIT', 'n_tokens_mistral': 2285, 'n_tokens_neox': 2077, 'n_words': 940, 'path': 'intro/intro-matplotlib-sol.ipynb', 'repo_name': 'ktakimoto/core-resources', 'size': '6835'}