Plots With Python

Posted By admin On 12/04/22

Sometimes we need to plot multiple lines on one chart using different styles such as dot, line, dash, or maybe with different colour as well. It is quite easy to do that in basic python plotting using matplotlib library. We start with the simple one, only one line. The plot method is used to plot almost any kind of data in Python. It tells Python what to plot and how to plot it, and also allows customization of the plot being generated such as color, type, etc. In Python matplotlib, a line plot can be plotted using the plot method. It plots Y versus X as lines and/or markers.

In our previous tutorial, we learned how to plot a straight line, or linear equations of type $y=mx+c$.

Here, we will be learning how to plot a defined function $y=f(x)$ in Python, over a specified interval.

We start off by plotting the simplest quadratic equation $y=x^{2}$.

Quadratic Equation

Plots

Plotting Data In Python

Quadratic equations are second order polynomial equations of type $ax^{2} + bx + c = 0$, where $x$ is a variable and $a ne 0$. Plotting a quadratic function is almost the same as plotting the straight line in the previous tutorial.

Below is the Matplotlib code to plot the function $y=x^{2}$. It is a simple straight-forward code; the bulk of it in the middle is for setting the axes. As the exponent of $x$ is $2$, there will only be positive values of $y$, so we can position ax.spines['bottom'] at the bottom.

Cubic Equation

Python

Next, we will plot the simplest cubic function $y=x^{3}$.

Since the exponent in $y=x^{3}$ is $3$, the power is bound to have negative values for negative values of $x$. Therefore, for visibility of negative values in the $y$-axis, we need to move the $x$-axis to the centre of the graph. ax.spines['bottom'] is thus positioned to centre.

Plot With Python Pandas

Trigonometric Functions

Make Plots With Python

Here we plot the trigonometric function $y=text{sin}(x)$ for the values of $x$ between $-pi$ and $pi$. The linspace() method has its interval set from $-pi$ to $pi$.

Python Plot With Error Bar

Let us plot it together with two more functions, $y=2text{sin}(x)$ and $y=3text{sin}(x)$. This time, we label the functions.

And here we plot together both $y=text{sin}(x)$ and $y=text{cos}(x)$ over the same interval $-pi$ to $pi$.

Plots

Exponential Function

The exponential function $y=e^{x}$ is never going to have any negative values for any value of $x$. So we move the $x$-axis to the bottom again by setting ax.spines['bottom'] to zero. We plot it over the interval $-2$ to $2$.