16. Python to make nice figures. Part II: basic plots
Oct 8, 2023
Part 2 of 3. Having discussed the hallmarks of a good vs a bad scientific publication (see part 1 https://youtu.be/rUV8VFbUi_U), we are now ready to explain how to use python to make plots. This video covers the basics of different python plots such as x,y plots, semilog plots, bar plots, pie charts, scatter plots, histograms, and more. Basic functions and keywords are described to show how to generate data, control markers, marker color, line style, legends, labels, and more.
00:00 import libraries
00:45 basic x,y plot
3:21 marker, line etc
7:20 plot legend
9:13 semilog plot
9:43 math LaTeX equations
10:56 font size
11:33 bar and pie charts
18:06 scatter plots
21:50 histograms
23:55 error bar plots
Hey everybody, this is Taylor Sparks again.
Now this is video number 2 of making nice figures in Python.
The first video talked about what exactly is a nice figure versus a bad figure.
So if you haven't seen that yet, go back and watch that one first.
Now in video 2 we're going to talk about the basics of doing really simple plots in Python.
And in video 3 we'll do some advanced ones.
So let's go ahead and get started with some basic plots.
First things first, we're going to need some libraries.
First off, we're going to import numpy as np
because numpy is going to be super useful for generating the data we need in the plots.
Then next we need to import the library for making the plots.
That's matplotlib.pyplot.
That's the library we're going to use.
We're going to call that plt is the convention.
So these are the libraries we're going to use.
Now let's go ahead and generate our data.
The first type of plot we're going to create is just a Cartesian coordinate x versus y sort of data.
So first let's get our x data.
We're going to use the numpy function np.arange.
Remember, arange gives you values between a start point and an end point with some increment.
So let's start from 0 and go up to 100, for example, every 10.
Now remember, the second number where it stops is not inclusive.
So if you actually wanted to go 0, 10, 20, all the way up and including 100,
then we would need to go above 100 because right now it's not inclusive.
So you'd have to go above that.
So just to show you what I mean, let's run that.
We'll now see that we have an array and it goes up to and including 100,
whereas if this had been set equal to 100, it's not inclusive.
If we run it now, you'd see that it actually only goes up to 90.
So let's assume we want it to go up to 100, so we're going to do 101 there.
Now next up, let's create some y data.
So y data, let's have it be equal to the x data,
and then we're going to have that squared.
Remember, to do squared operators, we're going to do **2.
So that should be all those numbers squared.
If we run that now by hitting Ctrl-Enter or F5,
we now have this variable here for y data,
and sure enough, it's all those values squared.
Now real data, maybe it's got some noise in it,
so let's generate some noise and then add them together using NumPy.
So we're going to have noise, we'll call that just noise,
equals, we're going to use NumPy again, and let's just have it be,
we're going to use the random function,
and then we're going to do randint,
so it's going to give us a random integer between two values.
So let's say it's between negative 10 and 10,
and then we want 11 of them delivered,
because that's how many there are in each of our data sets.
So let's run that now.
So now we've got noise, and you can see that it's just these random numbers
that go between negative 10 and positive 10.
What we want to do is for each one of these,
the one in the 0th index, we want to add it to the 0th index at y.
So you want to do element-wise addition of two lists or two arrays.
So the way that you do that is with NumPy.
We're going to call this, we'll call it yData.
We're going to overwrite our previous yData value.
This is going to be equal to numpy.add,
that's this element add-wise function,
where we're going to feed it yData and noise.
When we run this now, we should end up with our array for yData.
Now take a look at it.
We've taken the values which they were before,
and they've been modified to add some sort of random number
between negative 10 and positive 10.
So it makes it look a little more lifelike maybe.
So now we are ready to go ahead and generate a plot.
Making a plot is pretty simple.
You just do plt to call the pyplot function,
and then we're going to do the command plot,
and we're going to feed it the x and yData.
xData and yData.
Now there's lots of other arguments that this can't accept,
but let's just start with these two.
Let's go ahead and run it.
When we come over here to our plots panel,
you see that sure enough, we have something that looks like
x squared plus y squared.
Now if you saw our last video,
you know there's lots of things we'd like to change about this.
For one thing, we don't see any markers,
but if you have actual data points, it'd be nice to see markers.
Maybe we'd like a square plot.
There's lots of things.
We're going to put label axes on these.
So great, we can do that.
Let's start by making it a square plot.
To do that, we need to define a figure.
So we're going to say that fig equals plt.figure.
We're going to create figure number 1,
and then we're going to do a fig size.
It's one of the things that we can tell it.
So we're going to do fig size equals,
let's do a 5 by 5 inch.
So let's go ahead and run this now.
And now sure enough, you see that this plot has changed shape.
It's now square because it's 5 inches by 5 inches.
If you want it to be 3.5 because it's a two-column format
or whatever else, no problem.
You could do that too.
You could define it arbitrarily.
Great, now what about markers?
One of the keyword arguments for this plot function,
and again, you could look this up really easily.
You just come over to your browser
and just type in pyplot plot keywords.
When you do that, you'll find the documentation.
And here in the documentation,
you'll see all the different keywords that you can feed it
for markers, for line styles, for marker edge color.
All these great things are things that we can change in it.
So let's start right now by giving it a marker.
So our marker is going to be equal to,
we're going to feed it the string of 0 or O.
And that's going to create markers, which are circles.
There they are.
You could change the marker size.
Marker size equals, let's try putting a number in.
Let's try 5 right now.
I don't know what it currently is.
We put in 5, it got a little bit smaller.
Let's try 15.
That should get a lot bigger.
So you can do that.
You'll notice when we looked over here,
there's things like marker face color, marker edge color.
So you don't just have to have a basic marker.
You can make it pretty interesting.
So MFC, the marker face color,
let's make it white on the inside.
You can actually type out white, or I think just W will work.
But when you do that now, now you create it like that.
Maybe those markers are a little bit too big.
You want them just to be 10.
Figure out what you like, you can do it.
What about the line, right?
Let's keep on going.
Let's say we're going to use the line style keyword,
and you could do none if you wanted.
If you do none, then you'll just see your data.
Or you could do just the dash sign is what we saw before.
You could modify this, dash, dot, dash.
Oh, that's not the keyword.
Oh, right here.
Here's the line style, dash, dot.
I did one extra.
We run that now.
Now we'll get a dashed line between them with dashed dots.
Or dash, dash should give you just a dashed line.
So you won't know these things ahead of time.
You'll need to look them up.
But you'll find that once you do look them up,
they're pretty intuitive.
You can usually guess what you need it to be pretty easily.
You can change the transparency.
Alpha, let's set it to equal to 0.8.
So now each one of those markers is going to be
a little bit transparent.
See how we can now see the line underneath these markers
a little bit?
That's not super important for the plot how it is right now.
But if you have a lot of data that's on top of each other,
that becomes important.
So we'll show you that in a future video
in our more advanced topics, I think.
You can label your data.
So we'll say that the label equals data set 1.
So now it has the label,
but we're not seeing the label on the figure anywhere.
Well, that's because we haven't created a legend yet.
So let's go ahead and create a legend.
So we're going to do plt.legend.
And as simple as that, we now have a legend.
Now notice that it automatically picked a spot
for it to go on the plot, right?
It chose this top corner.
You can give it locations.
To do that, inside this legend function,
we're going to use the keyword loc for location.
And you can just tell it.
You can actually use, you can say lower right.
So that's going to put it in the lower right-hand corner.
So let's go ahead and run that.
And you should see that it creates it.
Yeah, it drops it down here now.
Now by default, it's going to do a pretty good job
of finding it, but that's one way to do it.
You can also send exact coordinates.
If you wanted to put it in a precise spot,
we'll show you how to do that in our advanced video.
But for now, let's just leave it as, you know,
just like that, it's going to do it.
And then plt.show actually shows the plot.
It's doing it automatically,
but if we're going to work with multiple figures,
it's good practice to actually show the figure
at the end of it, okay?
What else can we say about this?
Okay, let's say we wanted to show two sets of data
on the same plot.
Well, that's easy enough to do.
Let's go ahead and come here.
We're going to take our plot.
We're going to run it again.
This time, we're going to show our Y data,
but it's going to be plus, say, 500, right?
So if we run this now, let's see what happens.
So it automatically changed the color for us, right?
Notice that we've never defined our data set color yet.
So by default, it's automatically calling
the first one blue, the next one orange.
We need to change the data set name.
Let's call this data set two.
Right now, we have two circles, and that's not great,
plus the line styles are the same, and that's not great.
So let's make the line styles different.
Let's make the markers different.
So let's call this, make it a square
by using the S command, right?
And see how that looks.
Okay, there we go.
So now I've got two different data sets
showing up in this plot.
Now, this is a regular X versus Y plot.
We could also make it a log plot, right?
Instead of using the plot command,
we would do semi log Y
because we want it to be logarithmic,
let's say, along the Y axis, right?
So semi log Y and semi log Y.
Let's go ahead and plot those together.
And now, sure enough, you see that
it's done a pretty great job of making this
logarithmic on the Y axis,
but linear on this axis.
So now you can see how these two data sets
converge at higher values, okay?
Now, something that's really cool
is that you can use what's called LaTeX markup
or like mathematic scripting when you're labels.
For example, let's say we wanted to make the label
Y equals X squared, right?
So we would have...
We could just put...
So we have to use the dollar signs.
That means go into math mode.
And then you do Y equals X squared, okay?
When we run that now,
you'll see that the data set label
has changed from data set one to now.
Actually, it uses...
It actually put it as a superscript, the two there.
It looks like math font.
And then we could say that this one is the same thing.
We're gonna use dollar signs.
Y equals X squared plus 500.
Dollar sign.
We run it.
We've now got that really nice label.
Okay, really quickly, let's put labels on the axis.
All right, to create labels for the X and Y axes
is very simple.
We're gonna do plt for pyplot.
And then the command is xlabel, right?
And you can call it X variable.
You know, whatever that variable is.
Go ahead and call it.
And that's gonna create it for the X axis.
And sure enough, it shows up there.
And you do the same thing for the Y axis, Y label.
Now what if this font size is too small
for what you...
To match the figure in your paper, right?
So at the beginning of almost all of my figures document,
I have this thing here.
Within the pyplot library,
there's a way to update some of your parameters
like font size for the figure overall.
So it's a dictionary.
You can see that the keyword is font.size
and the value is 14.
So we're gonna use 14 point font.
I find that 14 point font is probably what you wanna use.
It does a really good job, I think.
Okay?
All right.
This is looking pretty good.
Let's go ahead and do a different type of plot now.
All right, so we're gonna make a new cell
by doing number sign, pound,
and then two percent signs, okay?
That creates a cell.
You can run an individual cell by hitting Ctrl-Enter.
And so it preserves this data
but allows us to work on a new cell down here.
So what are some other types of plots
that matplotlib can create?
Well, what if you have, like, categorical data
where you have, like, cats and dogs or whatever
and you wanna show the numbers of each of those
in a bar plot or a pie plot or something like that?
Let's go ahead and create our data.
Let's do it for the rings of power from Lord of the Rings, right?
So we're gonna say that the rings is equal to...
We're gonna create a dictionary,
so I'm using curly brackets.
So I have to put the keyword
followed by the number of it, right?
So let's do elves, elves,
and then we do colon.
And how many rings of power did the elves have?
Three, of course.
Then there was, what, the dwarves?
Well, let's do men first.
Men.
And then they had nine rings.
Then we had the dwarves.
They had seven rings.
And then finally we had the ring of power,
so we'll call this Sauron.
And there was just one of those.
So we've created a dictionary.
If we come over here to our Variable Explorer,
we now have a dictionary
where we have these keyword
and the value associated with them.
So what if we wanted to plot that?
Well, let's go ahead and create a figure
just like we did up above.
We're gonna grab this data.
We're gonna drop that in just like before.
Now, when we plot something,
we need an x and a y value.
So what we need to do is we need to be able to pull
from the dictionary
and create x data and y data.
Here's how we're gonna do that.
We're gonna do lists equals sorted.
So we're gonna sort our data
so you can rank it by alphabetically
for the elves, men, dwarves, or Sauron.
Or you can rank it by the items in the list
like the number of rings.
So we'll figure out how to sort it different ways
in a moment, okay?
We're gonna do sorted.
What is it that we're going to sort?
Well, it's our rings variable,
which we created above,
and then dot items.
So it's gonna be the items within our rings variable.
And then the key that we're going to give it
to tell it how to sort it
is going to be equal to,
we're gonna do this lambda function.
Remember our functions from before?
What was a lambda function?
A lambda function was what we called
an anonymous function.
It's the same as if you defined a function up above,
except you use lambda functions
when it's like a one-line-one use only, okay?
So it's going to be item is item
in the first position, okay?
So what that should do
is it should sort the data
by the one in the number one position, right?
And if we come over here,
that's gonna be the value, not the key.
So it should rank them from one, three, seven, nine.
Let's see if it actually does that
in our list variable that it creates.
So let's come down here
and hit Control-Enter to run that.
Sure enough, here's now our list variable.
Okay, it has created an array of tuples, right?
And in the tuples, we've got one for
Sauron one, Elves three, Dwarves seven, Men nine.
So great, it did rank them
from increasing number of rings.
If you wanted to do it alphabetically,
then instead of doing it off of the number one column,
we're gonna do it off of the zero position, right?
So if we run that now,
it should rank them by alphabetically.
Dwarves, Elves, Men, Sauron,
because it's ranking here and not there, right?
However you want to do it.
Let's assume we want to do it.
Well, let's show how they look, right?
So now we're going to go ahead and create a plot.
We're gonna do PLT.
This time, we're not gonna do plot.
We're gonna do bar
because it's categorical data, right?
It's like a string
and the number associated with that string.
So we're gonna do a bar plot.
Oh, before we can do it,
we don't have our X and Y data yet.
So we need to create our X and Y data.
The great thing is that right now,
this is stored as tuples, right?
And when we use tuples,
we can unpack them, right?
So you have two values here,
dwarves and seven.
So we want to store that into the two things
that we're going to put in our bar plot.
So here's how we're gonna do it.
We're gonna say that the variables X and Y
are equal to zip
and then we're going to do star lists, right?
So that's going to take
and it's going to iterate through each item
in the lists variable
and it's going to grab those
and it's going to put them in the two variables, okay?
So we do that now.
We should see, yeah,
Y, here's our Y values
and X should be our X values.
Just the names of those things.
Great.
So now we're ready to go ahead and make our bar plot.
So we're gonna feed it our X and our Y data
and let's take a look at the plot that it created.
There we go.
We have dwarves, elves, men, and Sauron.
And again, if we wanted to rank those by number of rings,
we would do it again
and now you'd see that they go from one to three
to seven to nine.
Great.
Now, what if you wanted a bar plot that went horizontally?
Great.
We can do those too.
So instead of bar plot,
we're gonna do a different command.
We're gonna do plt.barhx,y
and of course we can change colors
and everything like we did before
are also possible to change here.
Let's comment this one out
and now we're gonna do barh for horizontal bar plot
and there you go.
What if we wanted to do a pie plot?
Great, we can do that too.
Okay, we're gonna do comment that one out.
We're going to do plt.pie.
Now with pie, we're going to feed it.
Let's try xy.
Okay, with pie plots, you have to feed it the numbers, right?
That's the one, three, seven, nine.
That's y
and then you have to say explicitly the keyword
is labels equal x, right?
So that's gonna assign the labels.
So now we create, there we go,
a pie plot with these different things.
Now obviously a lot of pie plots you might have seen in the past
have separations.
That's called an exploded pie plot.
So great, we can create an exploded pie plot.
That's no big deal.
We're gonna create a variable up here called explode
and this is going to be equal to a list of values
on how far you want these exploded.
So if we do 0, 0.1, 0, and 0,
it's just gonna take the one in the second position
and pull it out a little bit from its neighbors.
Let's show you how this looks.
So we have to add the keyword here in the pie function.
We're gonna say explode equals our explode variable
and it's gonna take one of those.
The one in the second position was elves
and it brought it out a little bit, right?
So that's how you make these pie plots
and again, there's oodles of things you can do.
You can change the individual colors if you want
because these default ones were not amazing
but we'll talk about colors in our next video, I think.
Okay?
All right, let's talk about our next type of plot.
Create a new cell.
All right, this next type of plot is called a scatter plot.
In Python, scatter plots are useful
because it's a way to plot X and Y data
but you can encode color to a value.
So if you have like a color line
like going from blue to red, for example,
and you want that to correspond
to some sort of variable value
or the marker size,
you can encode both of those really easily
with a scatter plot.
Let's show you how it works.
First off, we're gonna need some data
for our X and Y data, okay?
So let's go ahead and create our X data.
So X data is gonna be equal to numpy.
Let's do arange
where we're gonna go from 0 up to 50 increments of 1.
We'll do the same thing with our Y data.
numpy.arange 0 to 50.
For a minute, let's have the colors
also equal numpy.arange 0, 50, 1.
Okay?
If we run this now, we have our three variables
for X data, Y data, and colors.
Okay, now let's have something
with the marker size to scale as.
So let's say that the area of these markers,
we want it to be equal to npy.random.rand.
We need it to have,
let's give it 50 entries, okay?
And then we're gonna make that,
whatever that number is, we're gonna square it.
So let's try that.
Let's make sure we have the right number here.
So area has 50, and our X data has 50.
So they're the right number.
Okay, good.
So now we have X data, Y data.
We have something for colors and something for area.
So let's try and create a plot real quick.
So let's grab our figure command from above
to make our figure palette.
It shouldn't have changed,
so technically I don't think we need this,
but it's good practice to include it.
Now we're gonna do plt.scatter.
We're gonna do X data, Y data.
We're gonna do color equal colors.
And then we're gonna do S, that's for size,
equals area.
Let's try that.
Okay, so instead of color, it's just C,
is the keyword that it uses for this function.
That's fine.
So we come over here now to our plot,
and you see, okay, check that out.
So our markers are too small.
Let's do it one more time to make those bigger.
So whatever we did for our area,
let's make these a lot bigger.
So instead of squaring it,
let's do this times 30.
Let's make it a little bigger.
Times 100.
Even a little bigger.
1,000 maybe.
Great.
Now, because these are overlapping a little bit,
let's fix that and do an alpha.
A equals 0.8.
Let's see if that works.
Alpha.
There we go.
Now they're overlapping a little bit.
Great.
So you can see what this is.
So our X and our data are just numbers going from 1 to 49,
from 0 to 49, right?
So that's why they're this straight line.
But you can see that the colors also go in a straight line
from low to high,
and they're mapped from going from purple to yellow
because that's the default color map that it used.
So you can see that this is a really cool way
to store lots of information
in a really information-dense way.
One plot can give you X data, Y data,
a variable corresponding to color,
and a variable corresponding to size.
So I'll show you in our next video
where we've done those in my research,
and it's actually a pretty powerful way
to plot lots of information on one plot
that makes it easy to interpret.
All right, let's go to our next one.
Make a new cell.
For this one, we're going to show you
how to create histograms.
Histograms are really important for data
that's in some sort of distribution,
like a Gaussian or a normal distribution.
Let's show you how we make that.
So let's call this our failure data.
Failure data.
And this could be failure strength or time or whatever.
So failure data.
Let's go ahead and create this using NumPy.
We're going to do the random function,
and from that, we're going to pull
from the normal distribution.
Let's give it a size.
Let's say size equals 200.
Let's do 300 entries.
And then we're going to multiply that by 200.
So now we've got our failure data.
Come up here.
It is 300 entries long.
You can see these now.
And they have been a normal distribution,
and then we multiplied that by 200.
Great.
So now let's go ahead and make a distribution.
So we're going to do plt using the histogram function, hist.
So we're going to tell it the data, failure data,
and then we're going to say bins.
How many buckets do you want to put this into?
Let's put it in 20 buckets for right now and run that.
Oh, that's not supposed to be capitalized.
That's lowercase.
There we go.
Try that again.
OK, there we go.
Failure data in 20 bins.
So sure enough, there we go.
Here's our data.
Let's add this and make it even bigger.
Let's add 3,000 data points.
The more data points that you sample, 30,000,
and then you put it in 20 bins, it's
going to start to look more and more like a Gaussian
distribution because it's pulling
from a normal distribution.
So if you keep on doing this and putting it in bins,
it's going to start to look more and more
like a normal distribution.
And that will get even better as you increase
the number of bins.
As we go from 20 to 200 bins, it's binning it,
and it's starting to look more and more
like a normal distribution.
So histograms are really a pretty cool tool
that you find a lot because certainly in data science,
you use this a lot.
You have to bucket your data into different categories,
and this is a great tool for that.
One last type of plot I'm going to show you
is how to do a plot with error bars.
So let's go ahead and create our data.
We'll say that x data.
This time is going to be equal to,
let's take a plot and have it be equal to 0
up until 2 pi.
So 2 times, we're going to do numpy.pi,
that gives us pi.
And then we're going to add .01 to it
so it actually goes all the way up to 2 pi.
And we're going to do that in increments of
numpy.pi divided by 6.
So that's going to create our values for x data.
For y data, let's go ahead and send this
through something like a sine function.
So we're going to do np.sine of our x data.
Now we're going to give it x and y errors.
So we'll call this equals...
Here we're going to do numpy.linspace.
It does linear space values between
a start point and an end point.
So let's go from 0 up until, say, 2.
And I think we need...
Let's try 12 first and see how many that gives us.
So we come over here to our x data.
x data right now...
I forgot to do numpy.arange, excuse me.
np.arange.
So our x data... Here we go.
Okay, so it's 13 entries long.
So here we're going to do the same thing.
We want 13 in our linspace.
So for our y error.
And sure enough, okay, we have...
The arrays are of the same size.
So now we can go ahead and come down here.
We're going to create a new figure.
And we're going to do plt....
I think it's called error plot.
Or error bar.
So here we're going to feed it the x data.
x data.
We're going to feed it the y data.
And then we're going to say that the y error,
yerr, is equal to the y underscore error data set that we had.
So let's go ahead and run that.
And there we go.
So you can see here that we've plotted our x data versus y data.
And it's showing it with error bars now.
Because we used this linspace function,
they are linearly getting bigger from 0 all the way up to 2
in equal increments.
And again, just like before,
you can do all the same things as before.
You can do marker equals...
Let's say we want actual markers for our data.
You could run that.
You could turn off the line.
So let's do line style equals none.
You could...
Let's do the marker fill color.
Marker fill color equals white.
And then let's do...
Oh, we can put ends.
We can put little arrows at the end of our error bars.
So that's called cap size.
So it's going to put a cap on it.
Let's do a cap size of, say, 5.
And let's try running that now.
Okay, there you go.
So here's our individual data points.
We can make those larger.
Marker size equals, say, 10.
So now we're going to have markers that we can actually see.
If you want to change the color and all that,
that's the idea behind adding this.
Now, just like we added y errors bars,
we could also add x error bars.
If you came over here, and let's copy this,
and let's go ahead and create our x error bars.
We could do that.
We're going to call it x error.
This one is going to be...
We'll do linear space, but it's going to go
from 0 up to only 0.1 maybe, or 2.
So now instead of just having y error equals y error,
we're now going to have another keyword of x error,
and that's going to be equal to the x error variable.
Okay, let's go ahead and run that.
And sure enough, over here, nothing,
because it starts at 0, but as it gets bigger and bigger here,
the error bars are just starting to get bigger
than our marker size.
Sometimes when they're smaller, it's fine,
and your publications just say that the error bars
were smaller than the marker size where you can't see them.
And where they're larger, you can't see them.
So those are the basic ideas for making
a bunch of the different types of plots
that matplotlib can make.
In our next video, we're going to show you
some more advanced plots with some real examples
of what we've done and how we made them.
Okay, see you in the next video.

