Matplotlib Tutorial (2021): For Physicists, Engineers, and Mathematicians

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Matplotlib is really useful, but I do get annoyed by those little inconsistencies. If I'm doing a simple plot and want to label my x-axis, I just use plt.xlabel('Something'). But when I want to do subplots, I suddenly have to use ax.set_xlabel('Something'). Same with xlim() and set_xlim(), for example.

There are tons of those things in there that could be streamlined, helping new users - and making it much easier to convert several plots into subplots by just copy pasting.

👍︎︎ 73 👤︎︎ u/space-throwaway 📅︎︎ Jun 28 2021 🗫︎ replies

One of my favourite discoveries with Matplotlib was the ability to export to pgf. That way you can pop them straight into latex docs as vector graphics and be able to change fonts, aspect ratios etc whenever you want without having to replot everything. I belive you need tikz to display them but cant remember off the top of my head.

👍︎︎ 38 👤︎︎ u/MostApplication3 📅︎︎ Jun 28 2021 🗫︎ replies

In this tutorial i discuss how to make line plots, histograms, surface plots, contour plots, and animations that are of sufficient quality to publish. One of the main libraries I use is called SciencePlots which makes the plots have an IEEE style.

Besides from being a plotting tutorial, this is also a tutorial in data representation for lab reports in undergrad. For example, I show how you might plot collected data vs. a fitted curve, and how to make an animation of a surface that represents something like the solution of Laplace's equation.

👍︎︎ 16 👤︎︎ u/JackStrawng 📅︎︎ Jun 28 2021 🗫︎ replies

If you are a physicist and plan on publishing papers, terribly looking ‘94 feelings plot are a de facto standard

👍︎︎ 11 👤︎︎ u/probablynotmine 📅︎︎ Jun 28 2021 🗫︎ replies

One thing I like to do when I have multiple subplots is use axes=axes.flatten() so I can loop through each subplot. Then I can put all of the common subplot adjustments in the loop. It can get more complex if you aren't plotting similar graphs in each subplot, but lately that's what I've been doing. For example, something like this.

fig, axes = plt.subplots(ncols=2)
axes = axes.flatten()
plot1 = dict(x=x1, y=y2, bins=20)
plot2 = dict(x=x2, y=y2, bins=10, density=True)
plots = (plot1, plot2)

for ax, p in zip(axes, plots):
    ax.hist2d(**p)
    ax.set_xlim(-0.5, 0.5)
    ax.set_xlabel('whatever')
👍︎︎ 7 👤︎︎ u/jampk24 📅︎︎ Jun 28 2021 🗫︎ replies

Although I appreciate the fun in learning something new, can you explain what the benefit is to doing this as opposed to using Tikz to plot the figures directly in LaTeX please?

👍︎︎ 6 👤︎︎ u/Wil_Cwac_Cwac 📅︎︎ Jun 28 2021 🗫︎ replies

I love how ugly the graphic in the thumbnail is.

👍︎︎ 6 👤︎︎ u/GustapheOfficial 📅︎︎ Jun 28 2021 🗫︎ replies

A lovely video, very useful with many helpful hints. My largest frustration with matplotlib is in trying to use a Times New Roman font. (It's for publication in a text.) Times New Roman is easy to implement in titles, legends, and so on, but when I use LaTeX in the titles, legends, the Times New Roman is replaced by the default font. Any suggestions will be welcome!

👍︎︎ 2 👤︎︎ u/BOBauthor 📅︎︎ Jun 28 2021 🗫︎ replies

I recently moved to Julia, and it's surprising how much more consistent the plotting interface is (in Plots.jl) -- you can use multiple backends (Plotly, Matplotlib) all without changing your code.

👍︎︎ 2 👤︎︎ u/hrvrd17 📅︎︎ Jun 28 2021 🗫︎ replies
Captions
today i'm going to show you how to make beautiful professional plots in the main plotting library of python matplot lib we'll start with basic line plots eventually getting to things like histograms 2d color plots contour plots and at the very end we'll look at animations my goal here obviously isn't to show all the features of matplotlib because there's so many but more so to go through my workflow in matplotlib how i approach making a plot the steps in coding that i take in order to make a plot look better and better and better and even the little techniques that i use in the process please remember to like and subscribe come join the discord server if you want to talk with other people in physics and math that share similar passions and let's get started so since this is a map plot lib tutorial um i'm only going to be importing matplotlib and numpy and we'll keep all the sort of physics-y sciencey stuff to as simple as possible in this video now matplotlib on its own doesn't actually make that nice of looking plots and so if you want to get a nicer format here i would recommend installing science plots and it just gives in some additional plugins for matplotlib so for example if i import these packages here and it allows me to use this plot.style.use you know that i've imported matplotlib pi plot is plt and i can specify some options so i think the best options are science notebook and grid like this so this just makes the figures look nicer and so we'll start with some quick plotting here so if you want to do a simple line plot right suppose i have some x data here x goes from 0 to 15 right and y is equal to sine x plus a little bit of noise and we want to make a quick plot here the simplest way to do this is just plot the plot xy of course this plot doesn't look great there's more features we can add but i'll show you what it looks like if i don't have science plots here so if i set it back to the default right this would be switching everything now so this is default then the plot looks like this and i think this looks gross this looks like someone took a crayon and scribbled on paper or something it's not it's not for me so i use uh the science plots and this is like professional paper paper um type plots and so you get something that looks like this but of course it has no labels um it's a shape kind of like a square and there's a lot of features that need to be customized here in addition this is a bunch of points but it's drawing lines between them so the first thing we might want to do is change how the line is actually drawn itself and so i can change the way the line's drawn for example if i give this option just this quotation this is the third argument here it draws it as a line as is if i go dash dash it draws it as a dashed line if i go o dot dash dash like this then it'll put a point at all the actual data points because what matplotlib does by default is it plots all the data points and then it connects them by these linear interpolated lines here and so if i actually want to see my data and then the interpolated lines i can go like this right and you see that the data is actually only at these blue dots here now if i didn't do the dot dot and just plotted the data it looks a little bit messy so this is where you kind of have to be artistic right you want to show a relationship or something that's happening in time if i showed you this you know you might not get a good idea of what's happening but drawing these uh interpolated lines i like to do it just dashes because this of course isn't actually real data this is just showing an interpolation then this gives more of a structure to someone when they're looking at it sort of like an object that you would see in real life of course i can also change the color too that's the other thing about the line i can go colors equal to purple red blue all the different colors work of course i can change the line width so for example line width equals 0.1 that'll make the dashed line really small you can play around with this right you'll notice what i'm doing i'm sort of re-running the code over and over and this is typically what i do when i make plots right and you can find a line width that sort of works so for example maybe i would want 0.7 so you see it but it's not overwhelming on the plot i can also change the point size too ms ms is for marker size i can make it really big but then it looks kind of gross i can make it small but then you can't see the points so you have to play around with these parameters until you find something that sort of works for your particular plot and it involves basically re-running the code over and over so now you know if you have some data some sort of uh x versus y data you can do most things like this right this is for the line itself of course something else you might want to do is change the figure size maybe you don't like this box here you want it to look a bit different so to do that you had a line before this and i would go plot dot figure if i can spell and i give the argument fig size is equal to uh say 8 by 3. i like that size so that's 8 and x and 3 and y so that gives like an aspect ratio here and i can do that plot and it looks a little bit maybe this is something you're going for in your plot but it gives it a different aspect ratio and you can play around with this right until you find a shape that sort of works for you for your particular plot um and i should put that here under where it says figure size now of course the next thing you want to do that of course you'll be docked marks for in any course if you don't do this and you'll be flat out rejected if you try to submit this to any journal is access labels so i can go plot dot x label and suppose i want to say like oh this is voltage and this is measured in v for volts and i can go plot that y label first of all this will be voltage the x-axis will be time in seconds so maybe you're measuring some voltage as a function of time here uh so that that's sort of typical what you might see you can add a legend to the plot as well um now a legend is usually if you have multiple things plotted on the same plot but uh you know for example notice how i'm adding things more and more to the plot but if i go plot dot legend and suppose i label this so i give an additional argument here to this plot a label is equal to maybe it's component one of my system then it'll draw a legend here and i can change the location of that i can say uh for example loc equals upper right and it'll put it in the upper right hand corner and i can put it wherever i want on this plot and so if i had two lines here i could distinguish between which is which with a legend and i can change the font size of that legend too for example font size is equal to 10 maybe the legend's too big and i get something that sort of looks like that so like i said it's easy to have multiple lines on the same plot and so maybe this is data that you measure in the true lab and you want to plot it next to a true sine curve to see what it looks like right and so this is data and you have this true sine curve here given by a function sine of x and so here i won't want to draw individual points i want to have a smoother looking green curve to plot over top and so you'll note that that'll show up in my plotting style right so here with the first component i use this particular style the second component where i'm looking at x2 and y2 i'm not going to use o dot dot because i don't want to put an o at the points i'm also not going to use a double a dash line here i'm going to use a single line and notice that my have more points 100 points between 0 and 15 is very dense i might change this color to green and then i'll call this component two for example and if i plot this you can see i have my sine curve next to this now maybe i don't like the dashed line anymore so i can get rid of this and i have the points and then i have my curve so this is like how the data is sort of looks like compared to reality which is this sine curve here and maybe you do a best fit and obtain the sine curve from this data so you can see already that there's quite a bit going on here now you'll note that the legend is kind of taking up some of the plot and there's many ways to deal with this uh one ways is by adjusting the x and y limits so maybe i still want this in the upper right hand corner but i need more space so i can go like this and if i adjust the y limit plot.ylim right and there's top and there's bottom so i can say top is equal to right now it's about 1.1 but see i had it set it equal to about 1.5 uh and it still doesn't have enough room for the legend but you notice that there's more room here than there is here uh the other thing i could do is i can make the legend um two columns so for that i would use the end call argument and call this equal to two and you'll note in this tutorial i'm sort of spitting out a lot of things really fast what i recommend is if you really want to learn matplotlib well then every little thing i'm mentioning like oh making the legend like this or like changing the y limits just write down these individual notes because you'll never know when you'll need them right and so this makes it a little bit easier and so instead of component one component two i'd probably label this data and theory for example because now my data are these points and my theory is that it should be a true sign curve for example um something that i deal a lot with in my research is histograms and so these are really important so here i just have a bunch of numbers right it's just a list of numbers and suppose i want to make a histogram of these values um well a quick histogram is just plot.hist res and you'll see it returns uh two objects here it actually returns the edges of the bins so this would be like um so the edges of the bins are here uh and then the counts in each bin so that says there's two between these two values 15 between these two values et cetera et cetera so if i say like a is equal to plot.hist i can actually extract a as two numpy arrays here if i wanted for example to get the bin edges and the number of things in each bin that's a little trick for matplotlib now maybe i don't want this many bins right this is the default number of bins well i can set bins is equal to 100 for example and i don't want to set it equal to a but i'll just go plot dot show and you'll see now there's 100 bins but maybe the histogram is a little bit too sparse i have too many bins right so if i make the histogram too dense sorry there's too many bins here then there's not enough things to fill each bin so maybe here i want 30 bins for example i can get a decently good looking histogram and i'd also probably want to change the figure size here i like that eight by three a ratio so now i get a histogram that kind of looks like that uh but here's the it shows the number of entries on the y-axis maybe i want a normalized histogram which means that the area under this is equal to one well from that i could choose the argument density is equal to true and now it'll plot a density such that the area of this thing is equal to one so this is now a density plot as opposed to a histogram and this is more popular because suppose you collect um suppose you collect data and you collect ten thousand things one time you collect thirty thousand another time and you plot two histograms over top of each other you want to compare them even though you don't have the same number of data points so i prefer density plots a lot of the times um yeah so this is what i did here so i'm just gonna get rid of this and i can also use a different style of bins now sometimes you want to put two histograms on the same plot and that's kind of annoying when they take up space like this because maybe i have another one that's a little bit wider and if i plot them over each other then one's going to be covering the other one this shows up a lot in my research so maybe i have these other residuals here as well or they're just an array of values well if i go like this for example i just plot them over top of each other like this you'll see that they cover each other and you can't actually extract what you want from here no one knows what's going on with the blue um but what i can do is i can go uh hist type is equal to step you'll see what this does and this is my favorite argument for histograms here and now you can see that it only draws the top of the bars and this makes it very easy to compare histograms on the same plot for example so very useful to keep track of that as well now so far i've only used a very basic api in matplotlib but typically sometimes you're dealing with multiple plots on the same figure for example i call them individual axes and then you have a figure that contains many of those um and maybe you want to add text to plots that's kind of tough with the basic api if it's complicated and then creating animations you also need to use this more advanced api and you can do more with it but it just requires a little bit more uh coding and it requires uh defining things a different way so for example you have to use fig x is equal to plot uh dot i always use plot.subplots uh one row by one column so you see what i'm doing is i'm creating you create an array of plots on the same plot but i make it one by one so it's just one single plot a fig size and you'll see that come up more later in the tutorial and i'm gonna make the fig size a 12 by four and it creates a figure and there's one ax called ax on this figure and so i could make it one by two for example and then i have two plots you notice that one row by two columns that's what's going on that's what you see here um but right now i just want one by one so this creates my uh figure and then i do all the same commands as before x dot plot x y and then o dot dot everything looks very similar to before and x instead of x label and y label it's actually set underscore x label so you normally you have plot dot x label and plot dot y label here it's a ax dot set x label so i can set whatever you know i'm not super interested in uh you know whatever but you can set your x and y labels like this and do all the same thing that we did before and uh plot.show will show it right so this is like a slightly different api but you'll see later that this comes in handy especially like i said here multiple axes in one figure so you know suppose i want to do this and maybe i want three rows by two columns plot i need to make sure that the figure size is appropriate for this so 12 by 4 right if i have three rows by two columns this isn't going to work so maybe i want um 12 by 12 here [Music] and so now my axis if i just look at this if i look at axes here i actually have a 2d array of axes and each one contains a separate axis so i need to index them appropriately right so i can go like this and uh you know suppose i want to select one right well i would go like this this is how i do it the work flow that i sort of use here so i'd go x equals axes zero zero so zero zero means take the top left one zero one means take this one one zero is this one one one is this one so zero zero is the top left and then i would do everything i need to do to the first axis in a couple lines of code and if i want to do something to another axis right so then maybe i want to make a histogram at uh 1 1 for example so that would be this plot here i could go x dot hist and it's just all the same arguments that i'd have here right so suppose i do this x.hist all this stuff here and it sets x labels and y labels and you see that i have my things show up here like before i can add anything um sorry multiple things to each plot here like i did before and i can add legends to each axis i can do all that for example if i label this label equals you know component one i'll just call it comp one and then i can call for example ax.legend here and it will give a legend in this particular axe axis of the figure so it's very easy to general generalize this sort of thing and uh have code run like this so this is multiple axes in one figure i can also set titles to each axis so ax.title um histogram right this is my plot that is my histogram and you have to use set title for axes not just ax.title and so i could label each one of these appropriately as i see fit another thing that's really common is you might want to add text to part of a plot here and so for that for example suppose i want to add text to this axis well i'll make sure i'm in this code here so ax dot text and 0.1 comma 0.1 that'll just go here and then this is x so as this gets larger it goes to this side of the plot and as this second argument gets larger it goes up like this so that's how you label that so 0.10.1 is near here i would normally experiment with some values until i find something that looks nice and i could just call like text that's the text here for example the string that i want to put and uh you know if i just put 0.0 0.1 0.1 it will go to 0.1 here it'll take the literal values here from the plot but i like using sort of a dimensionless way so that 0.1 or 0 0 corresponds to here and 1 1 corresponds to here so you can do it regardless of the dimensions of your data and for that i call transform equals x dot trans axes and so this is just an additional argument you need to add if you want zero zero to correspond here and one want to correspond here and i can add text and you'll see that the text shows up here and i'll get into that a little bit more later as well there are other things too right i'm going to keep adding things in this tutorial for things to know maybe you don't like these numbers they're too big maybe i want to make them smaller well i can go like this axe dot tick underscore params and i would say axis equals both i want both the x and y axis of this plot and i want to say which is equal to well don't worry about this argument i guess and label size is equal to 10. so it sets my font size here equal to 10. so now on this plot you'll see that the numbers are a little bit smaller and then maybe you want to do that for all axes as well to make it look a little bit nicer so again these are all sorts of things that you can play with and i'm just sort of handing things out here again take notes on this it'll come in handy and this stuff will show up so as an example i'm going to create a plot that i think is sort of what i would call a professional plot first like something i would put on my thesis for example or something you might see in a paper and it requires putting a lot of data on one plot here so i have these four arrays whereas a one reside two raise a three would say four or b a one a two and b two uh and they're just sort of things that i'm gonna make a histogram of and so a one corresponds to one thing and b one corresponds to another so suppose i'm collecting data for two different processes a and b and so this is trial one and this is trial two and i wanna put trial one on one histogram then maybe i fix my equipment i do it again and i have uh the second trial with the new data and so i have four arrays here and for example if i'm doing stuff really quick i could go plot.hist res a1 with 100 bins and uh make sure i have plot.show as well and uh for example this is very quick what you might see with the data but you can see 100 bins is obviously too much and this is not a great looking figure size um there's some text i'm going to add i'm going to add the standard deviation of these right because these are histograms which means they have a width to them and i'm going to add the the standard deviation of these so for example i have these two text strings here and all it is is it's latex code with this is slash n means new line so this is on one line it's going to print sigma a is equal to and this is using f strings of python is equal to the standard deviation of res1 with four decimal places and then um sigma b for trial one is equal to the standard deviation of this i do it for text string two as well this makes it easy to add this text to the plot so i do this beforehand uh now for making the plot so fig axis is equal to uh plot dot subplots and i make one row by two columns remember two columns so the plots are going to be like this this is for trial one then maybe you're experimenting you fix your equipment you collect these two arrays and i'm gonna put these on the other plot as well uh for a good fig size i found here uh was about 10 by 3.5 so for example this is what i'm creating and i'm going to put trial 1 my first data here and my second run of this data here for process a and process b so it's kind of abstract but man whatever then the first thing i do is i want to deal with this axis so i go x is equal to axes zero so that takes the first one here um you'll note that here i had it indexed as axis 0 0 because it was 2d here because it's a 1d i can just index the first element and it's just a one-dimensional array then i can start plotting things so x.hist res a1 and it does something like this and i'm going to add plot.show at the end plot that show basically gets rid of all this stuff here oh when i do this so okay it's not exactly what i want maybe i want uh 30 bins and i want to make it a density plot like i said when you're comparing data together and his type is equal to step and so this looks good and now i can plot the other thing on this plot as well res uh b1 so i have two things on the same axis i also want to label this so this is uh label is equal to process i'll just call it a and this is uh b [Music] and i want to add a legend x.legend and i'm going to add it to the upper right so i need to call uh loc is equal to upper right and now it adds a legend here so i know which part which is process a and which is uh process b here um some other things i want to add the text here from this so i can go ax dot text i found a good location with 0.05 so that's like right near here and 0.81 which brings you up here 0.81 and i'm just going to add text string one and i have to add transform equals um x dot trans axis like this so now i have this up here but you'll note that there's these grid lines and it doesn't look that great and so i'm going to add a white box around them and for that i need to call um v box is equal to dictionary and now i pass in some arguments face color is equal to white and edge color is equal to black so matplotlib sometimes works in these weird ways where it passes arguments but this is basically passing an additional thing called b box and uh with specifying the face color and the edge color in a dictionary and so now i have this nice box around here and uh for the legend i don't want this fancy box i also want this to be a little bit more square so for this i call fancy box is equal to false and you'll note again there's all these weird arguments in matplotlib i also want the edge color to equal black so now it matches this so now this is starting to look a little bit nicer right and i can set my y label for example x dot set y label i'm going to call this density and x dot well because these are the same units i'm actually going to use a fig sub title here so fig.subtitle this is a if you want to add a label to a figure right i can add labels to the individual axes i can also add a general figure subtitle here so i want to add it down here and uh not subtitle i want to add text so i'm going to add it at 0.5 so it's in the middle in x negative 0.04 so it's slightly outside of the plots of course and i'm going to call it maybe i'm measuring delta e so change in energy of some sort of process you know something abstract and it will add this in the middle i want to make sure it's centered so i call um where is this here see sometimes the arguments are not so easy to remember a horizontal alignment h a is equal to center now i have this in the middle and maybe i want the font size equals 20. so it shows up so now this sort of applies to both things here and it's measured in joules for example so i can say joules and now i have this x label that applies to both these here and basically i do the same thing as i did for this axis for this other axis only this time i'm plotting a2 and b2 and i'm adding text string two here that corresponds to the uh where is this text yeah text string two which corresponds to the standard deviations of the second process and i need to make sure this is axis one and now i have uh this here and this here and maybe i don't like green and blue right well i can label this uh color is equal to blue i actually don't like the default colors very much i prefer these colors here so blue and red and note that this has a little bit of a stronger look to it this is more in my opinion it's more professional maybe some people don't prefer it but i like my plots to look thick you know have nice colors like this and maybe i don't want a legend on the second one right maybe you don't want the legend here so i can get rid of the legend on the first axis again the important thing here is not only learning the code but the sort of thought process you can see what i'm thinking as i make this and i don't want this repeated right i want a y label that sort of uh sort of corresponds to both plots because this looks kind of ugly so i can also get rid of the y label from this plot and now i have a nice looking plot right and maybe i want to give a title to each axis that's an option too i can go ax dot set title this is trial one and i can do that to the other axis as well trial two and this in my opinion is a very nice looking plot right you have the standard deviation for both trials you have a legend here that tells you which is trial a and which is trial b uh if i was going a little bit more advanced i might somehow color this but then sometimes that doesn't look very nice either but this is a really nice plot here of plotting histograms on the same plot of course something you also deal with all the time is if you have a something that's a function of two variables for example z that's a function of x and y you can no longer plot it as x versus y you need a two dimensional plots and maybe 2d is the wrong term here but what i mean is two independent variable plots so for example here i'm creating an array zed that's a function of x and y so x y and then z is some surface how would i plot that right and there's many ways to do this and this sort of data comes up all the time and you could make a 3d surface plot and i'll show you how to do that but it's typically not the ideal way to deal with these sorts of problems um uh one way is a filled in contour plots this is sort of like a color plot per se so i can go plot dot contour f this f is for filled in and i just give x y z and it'll make a contour plot like this and so wherever you see the same color this is sort of the same value now obviously it's not discrete like this like this isn't all the same value that's because there's a specified number of levels and i can change that levels is equal to 30 for example now you have more of these contours right that's what a contour is it's a line of a constant value and now you can see that the function gets higher here and lower here but what do the colors actually correspond to right and for that you probably need a color bar and so now i have a color bar on the side that tells me the value corresponding to what color right and i can set labels for my color bars right uh label i think you do it like this and i've got asd showing up here so i can put a quantity here maybe i'm measuring like the voltage in space like i have a a table and there's you know some sort of configuration here and maybe the voltage is high here and here and then i would label this voltage for example um you can make them more dense by changing the levels as i've said you can use vmin and vmax to adjust the color range so for example maybe i want everything under 0.72 to be the darkest color well then i would go i would add this here v min equals 0.7 right and now everything that's 0.7 or less is going to be the darkest color so that's the minimum value i can do the same thing with the maximum maybe i want everything over 1.68 to be um the brightest color so then i would go v max is equal to 1.68 and now everything that's greater than 1.68 is this yellow color and now it isn't really useful for this example but you know suppose you're plotting a one over x function or something that diverges a function gets really really big maybe it's like in this range and then all the sudden shoots off to infinity that can be really useful so that it keeps the color range in the area that you're interested in for example if it suddenly started increasing rapidly here and went up to 20 then i might want to set it only in a small region right then i might want to set the max equal to 1.92 so again things to consider when you're dealing with these plots uh maybe also you don't like this color map as well and so i can change the c map argument c map is a plasma for example that's a different color map and it changes it here and if you want to look at all the different color maps in matplotlib i think they have them all right here so if i click on this it would bring me to all the various color maps the options here and so you just give this number as a string and it will use this as your color map for example now sometimes you actually want a pure contour plot which is actually literal lines like you might see on a map for example lines of constant altitude and that's preferable in some cases and so you could go plot dot contour xyz and it actually plots these lines of constant value and now this doesn't look really good because you don't know what value these are the colors are kind of weird and this is the way that i like contour plots the best so first of all i save this as an option as a as an object that's uh you know it keeps this information here then i can add these color labels to this plot so i could go call plot.c label and then i pass in cs so it know it has access to this information and watch what this does i can get font size is equal to eight and it actually will write in the value of each contour here and so this is really useful because rather than having to look at some color legend or whatever you can see the values specifically here and if you don't like the number of lines if you want there to be more lines you can add more same as before levels equals 20 for example and you get something that looks a little bit more dense and i like this right this is a really nice looking plot you have a combination of the colors which sort of guides your eye to making it look like it's larger but then you can also see the specific values themselves so contour plots even in courses like e m and stuff when you're plotting potential uh you know lines of constant potential are an important concept in e m and so this sort of plot is useful finally you could create a 3d surface plot directly and this isn't a great option i would say and i'll show you why so fig access subplots and here i need to add a certain keyword argument subplot underscore keyword argument is equal to a dictionary like before and uh notice how this comes up in matplotlib projection is 3d and there's something wrong here and that is because just give it like this so i'm used to doing dictionaries with curly braces and now it creates this 3d plot like this and i can plot the surface as follows x dot plot surface x y it said and i'm going to use a cool warm color map so that's one of the ones options here and you see that you actually have this surface plot here now the problem with surface plots if you put them in a paper or something is that you know we have the color here to at least tell us which part is higher but it's not really obvious what this looks like right unless you have like a full sort of 3d objective view this isn't that nice now i'll show you in a bit how to make an animated gif of this where it rotates around and then in that in my opinion in that case this is a much more preferable plot but just like this it's it's not a very nice looking plot stream plots are really useful for plotting vector fields so here i have some x and y data that's just a mesh grid right and u and v are specify the x and y component of my vector field so at every point in space there's a vector and this speed here is the magnitude of the vector so i also keep track of how big the vector field is there so maybe you have wind it's really windy at some parts pointing in one direction it's not very windy in other parts pointing in another direction and that's contained by u and v so i'm going to make a four by four plot here showing all the different options you can do for this fig axes is equal to plot dot subplots i want to make it uh two by two and fig size it's five by five so i'm gonna do a different thing in every one of these little axes here i'm gonna make it actually 7x7 uh so the first thing i'll do is i'll start with my first axis and i'm just going to use the regular stream plot so ax.streamplot it has to take in my x and y mesh grids and also my u and v components and it will just make a stream plot here right this is kind of nice because it tells me which direction the flow is right so it's almost like if this were a water stream this is the direction that it would flow but it doesn't really give you a sense of the magnitude of these vectors for example you don't know if it's flowing faster here or faster here and so in order to find that out i can go a different plot and i can actually change the speed based on the color um string here color equals speed because i've defined the speed here and so it uses the regular um thing so it means that whenever it's yellow it's going faster and purple is slower but in my opinion this still doesn't look great and there's actually a way that i think is the best to do this so i'm going to make it on this bottom plot here one zero and i'm gonna define this thing called the line width so i'm gonna change the line width based on the speed and i think this is sort of a a more artistic way to do this that looks better so i'm gonna change it to five times speed it's gonna be proportional to the speed divided by speed.max so the the largest line width is equal to five or so the largest line width is equal to one and then it gets less than one and so here i go uh line width is equal to our line width that's the argument is equal to lw and now on this plot you see that these larger line widths are where it is faster so you can see there's not much flow in the center and it gets faster moving outward i think this is preferable to this plot uh here and you can also look at lines of constant flow for example if i start at a particular point and i'm in the water for example how am i going to move well that's what i'll show in my final uh plot here so i like this line width here uh feature but maybe i don't want it for the um you know line of constant flow and so i can make a start point is equal to and i'm going to make these seed points so seed points this is the example of some starting points and it's an empty array and my first starting point is going to be uh at zero one and my second point will be at one zero so this is x y so x is zero y equals one and uh x equals one and y equals zero so i'll start here and start here and it will plot the lines of the direction of which i'm going to flow so my seed points here are x equals zero y equals one that's going to be my first starting point somewhere here and my second is x equals one y equals zero so start here and i want to look at the lines that the flow that i'm going to do so only those particular lines and so i can plot that like this and you see that this is the one zero point so this is the flow line corresponding to that point and this is the flow line corresponding to the other point so another feature of these vector plots that i think is pretty cool image reading is really easy using matplotlib and they have a function to actually open png images so here i have an image of a flower saved as a png and i open it and it automatically will open the pixels into a numpy array and if i want to plot the image plot.m show m and it will plot that image on a plot here so again really simple and i don't want to get too much into this but image reading is very another thing that you could look into in matplotlib for sure so the last thing i want to look at is animations or making animated gifs in matplotlib because i do this in a lot of my videos and i think it's a really cool feature of matplotlib so for example this function here f x t is a sine wave x minus three t that moves at three meters per second so i can plot at any point in time any given t i can plot the sine curve the question is t increments the sine curve sort of moves to the um the right here right so it's moving over as a function of time as time gets larger and larger and larger the sine curve will shift on the plot and so can i actually make an animation of the sine curve moving over well i can and so let's let's start sort of basic here so i can plot that plot x and f of x zero right and the sine curve looks like this now over top of it i could also plot 0.1 right so here time is incremented a little and it's moving over to the right a little bit and of course as time increments more one it moves you know over here to the right and a 1.3 for example it's it's sort of moving over more and more and more and i want to make an animation of this blue curve here just moving over on a plot and so i can do that pretty easily so i need to import the animation libraries animation and pillow writer and this is how you do this so it's it's pretty similar for every time you want to make an animation it's it's always sort of the same thing so i need to use this api the fig x1 plot that subplots one by one and fig size i'll make it eight by four i think that's a good figure size so this is the axis of which i'm gonna make the animation on uh i'm before i make the animation i wanna store this empty line data and empty time data so i'm going to display the time and i'm also going to plot the thing but i want to make those objects but not initialize them with anything yet and so for example i can go line 1 is equal to dot plot and it's just going to be empty right so i'm plotting an empty line here so nothing shows up uh same thing with this uh text so i'm going to call this time text zero the ax dot text i'm going to put it at 0.65 um 0.65 0.95 and uh no text right so it's empty right now and uh font size is equal to 15 uh and i'm also going to use uh transform i'm just going to copy from what i had before see i'm lazy it's not good to type this all out every time uh yeah this is what i want [Music] so i have all this stuff that i want so it creates an empty time text with nothing in it so far and an empty line and we're going to add to these lines and change them in an animation and so for this you need to define an animation function first i'm actually going to set the x limb and y limb 0 to 10 times mp.pi x let's set ylm set at minus 1.5 to 1.5 otherwise it will keep those initial limits and so this is the sort of limit i'm looking at here which translates to right i'm plotting from 0 to 10 pi here so that sort of translates to our problem and so now we need at each frame of the animation we need to update it and for that i need an animation function which we call def animate and all it takes in is the frame number i and so we need to change the animation as a function of the frame number and so here i'd go line one dot set data and i'm going to set it to x and f of x and now i need to have some time at t right uh related to the frame number so if i go 1 over 30 times i right then the time is 130 130th the frame number so this is something you should have to think about but if i'm making an animation at 30 frames per second which i'll show you how to do later 1 30th times i means that every second or every 30 frames they're equivalent right 30 frames per second is 30 frames in a given second i'm going to increment t by 1. so that's how you relate this right the frame number you have to think about what you're doing here if i was going 50 frames per second which i'm actually going to do because 50 frames looks nicer then every 50 frames or every one second t goes up one right so at the 50th frame or after one second this is going to equal to one after the 100th frame or two seconds this is going to equal to 2. so you have to adjust this appropriately and i'm also going to time text so these objects are initialized up here but i changed them here dot set text and i'm just going to go t is equal to two decimal places dot format and the time is going to be i divided by 50. so this is the time that's going on here and now to animate i go any is equal to animation dot funk animation i pass in my figure i pass in the animate function that i've defined personally i'm going to go for 240 frames uh interval doesn't really matter for what we're going to be doing interval equals 50. and so this sort of creates the animation but then i need to save it as a gif to my computer and that's where you specify the frames per second so i go any dot save i'm going to save it into this folder images slash any dot gif the writer i'm going to use is pillow and i want to save it at 50 frames per second right that's why i put this 150th here so fps is equal to 50 and the resolution dpi is equal to 100 and so then i can create this uh animation here okay so the animation has been created you can see it's a gif and the time increments from 0 to 4 and my curve is moving over to the right just like i want it to so very easy to make an animation in matplotlib now you'll recall earlier that i had this surface plot that i said didn't really look that great but we can make an animated gif of it rotating to make it look a bit better and so it's the same sort of procedure that you do up here so i'll copy and paste this code this is the surface of course and so i just need to change a few things to make it work well so instead of having this line one and uh text here i just go um x dot plot surface also i'm gonna use the default map plot lip here i know i said it looked ugly but um default i think it looks better than this one for the surface plots so uh you know sometimes it's better and i'm going to use c map is equal to cool warm line width is equal to zero to get aliased it's equal to false these are just some arguments that i had here and my initial viewing angle i specify the azimuthal and elevation so my elevation is going to be 10 degrees my azimuthal angle is going to be 0 degrees and now i want to make an animation and i want it to be a gif such that it rotates and at the end it gets back to its initial position and then it rotates sort of continuously right and so i can uh put that in appropriately with the animate function so here i just go change the viewing angle that's all i really need to do so i go x dot view in it and i'm going to make the azimuthal is equal to 3 times i so that means every frame it moves 3 degrees that's pretty simple and so in order to go a full 360 degree rotation i need 120 frames and i'm going to save it at 30 frames per second and i'm going to call this any two and of course there's an error and that's because xtop i need to change this as well so subplot keyword argument i need to make sure that it's actually 3d so now make sure that it's a 3d plot i can plot this and it will save a second animation here and so now you actually have the surface rotating and so it's a lot easier to see from the past example so this would be one of the rare cases where i think it's appropriate to have a a surface plot like this before i finish one thing i should mention is suppose you have a nice plot like this and you actually want to save it to your computer well that's one final command and that's plot.save fig and i specify for example i want it as plot.png uh dpi is 200 so 200 i find is a good high resolution plot here so if i rerun this and it's back in the basic style of matplotlib that's fine by the way this is what it would look like in regular matplotlib you can see why i like the other one better and i can actually open this and i have a full resolution png plot and you see that it looks really nice even the regular map plot limit in this case looks decent anyways i hope you enjoyed this tutorial if you did please like and subscribe and i'll see you next time
Info
Channel: Mr. P Solver
Views: 9,876
Rating: undefined out of 5
Keywords: python, numpy, matplotlib, plotting, tutorial, python tutorial, python tutorial 2021, matplotlib tutorial 2021, physics, how to plot in python, how to make graph in python, python physics, scipy, sympy, how to, differential equation, calculus, engineering, plotly, 3d plot, 3d plot python, python animation, python gif, how to make gif in python, gif in python
Id: cTJBJH8hacc
Channel Id: undefined
Length: 47min 59sec (2879 seconds)
Published: Mon Jun 28 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.