Creating Column Charts with Matplotlib
Zenva
ACCESS the FULL COURSE here: https://academy.zenva.com/product/bite-sized-coding-academy/
TRANSCRIPT
So let's get started with some imports. And so the first thing we need to import is of course matplotlib and all of the plotting functionality is in a submodule called pyplot. We want to load our data with open, and then inside here we want the file name. And our data's stored in a file called fruit-sales.pickle. And this would just open it as a text file, but for efficiency I've saved the data in a binary format, so we have to tell Python to read from a binary format, so that's what this RB stands for. So we're now reading binary data and then as F links this, it creates a variable F that represents this file. Okay and then I use a colon here to setup an indentation block. So inside of this block, now I can do anything with F, this file, that I want, and then after I get out of this indentation block it will automatically close the file for me. So then I'll just load my data. So let's see our data, let's see our data somewhere on this guy. As you can see we have, it's actually a list of tuples. Each tuple has a name of a fruit, and then the quantity that sold. So it's in this format, but what we can do to make our lives easier to work with, is we can split this list of tuples out into two separate lists. So essentially, we'll have one list that has all of the fruit, and another list that has all of the numerical values. So using a Python function called zip, so I can say fruit and num_sold equals zip, and then there's a special operator that we have to use here, there's a special syntax. It's star, or asterisk, and then data, and what this does is this is going to split our list of tuples into two separate lists. So fruit will have all of our fruit here, and then num sold will have all of our numerical data. So this is what we want the result to kinda look like. We need to tell matplotlib where to put these bars. so we need to create a list where we say zero, one, two, three, and then we can give that to matplotlib, and matplotlib will know where to position it. Bar coords, range, length of fruit. So what this will do is this will create essentially a list that goes from starts at zero and goes up to however many fruit we have. Plt.bar, and the first input to this guy is going to be these coordinates, so I have to tell matplotlib hey here are the coordinates. And then the second argument is how tall do I want the bars? And that's just the num_sold here. Now this is going to setup our bar plot, and then to show it we have to call plot dot show. so I'm gonna call this guy and now that I have this I can actually run this and we should be able to see our plot. So here is our plot. So you see we have these bars here, and their positioned at zero, one, t ... https://www.youtube.com/watch?v=FP7vUdC7eY0
5806524 Bytes