Login

Sign Up

Matplotlib in One Shot(Practical)
_Ujjwal_

Posted on May 26, 2025 | AIML

Matplotlib in One Shot(Practical)

Plotting Your First Graph with Matplotlib

If you're getting started with data visualization in Python, Matplotlib is one of the most popular and powerful libraries you'll encounter. Let's walk through how to create your first simple line graph using just a few lines of code.

Matplotlib can output graphs using various backend graphics libraries, such as Tk, wxPython, etc. When running python using the command line, the graphs are typically shown in a separate window.

import matplotlib.pyplot as plt
plt.plot([3,5,8,6,2,1])
plt.show()

Output:
Image_1
the plot function is given one array of data, it will use it as the coordinates on the vertical axis, and it will just use each data point's index in the array as the horizontal coordinate.

plt.plot([-3, -2, 5, 0], [1, 6, 4, 3])
plt.show()

Output:
image2

Another view

import numpy as np
x= np.linspace(-2,2)
y= x**2
plt.plot(x,y)
plt.show()

image3

Code Explanation

  1. import numpy as np
    This line imports the NumPy library, a fundamental package for numerical computing in Python, and assigns it the alias np. NumPy provides powerful tools for working with arrays and mathematical functions.

  2. x = np.linspace(-2, 2)
    np.linspace(start, stop) generates a sequence of evenly spaced numbers between -2 and 2.
    By default, it returns 50 values, including both endpoints.
    These values serve as the x-coordinates for the plot.

  3. y = x**2
    This computes the square of each value in the x array using element-wise exponentiation.
    The result is a parabola, since the function being plotted is:
    $$ y = x^2 $$

  4. plt.plot(x, y)
    Plots the x-values against the corresponding y-values.
    Since both x and y are arrays of the same length, this creates a smooth curve of the function:
    $$ y = x^2 $$

  5. plt.show()
    Displays the graph in a new window or inline (depending on your environment).
    This is required to render the plot when running scripts outside of notebooks.

Line style and color

plt.plot(x,y, 'r--')
plt.title('Square Function')
plt.xlabel('x values')
plt.ylabel('y values')
plt.show()

Output:
image4

x = np.linspace(-1.8,1.5)
plt.plot(x,x,'r--',x,x**2,'g:',x,x**3,'b^')
plt.show()

Output :
image5

Multiple Plots with Different Styles

This line creates three different plots on the same set of axes, each with its own color and line style:

🔹 x, x, 'r--'
Plots the identity function
$$ y = x $$
'r--' specifies a red dashed line (r = red, -- = dashed).

🔹 x, x**2, 'g:'
Plots the square function
$$ y = x^2 $$
'g:' specifies a green dotted line (g = green, : = dotted).

🔹 x, x**3, 'b^'
Plots the cubic function
$$ y = x^3 $$
'b^' specifies blue triangle markers at each data point (b = blue, ^ = triangle-up markers).

By combining multiple (x, y, style) sets in one plt.plot() call, you can overlay multiple lines and functions on a single plot.

** plt.show() **

Another view

x = np.linspace(-1.4, 1.4, 30)
line1, line2, line3 = plt.plot(x, x, 'g--', x, x**2, 'r:', x, x**3, 'b^')
line1.set_linewidth(3.0)
line1.set_dash_capstyle("round")
line3.set_alpha(0.2)
plt.show()

Output:
image6

Image Save

x = np.linspace(-1.4, 1.4, 30)
plt.plot(x, x**2)
plt.savefig("my_square_function.png", transparent=True)

Subplots

plt.subplot(2, 2, 1)  # 2 rows, 2 columns, 1st subplot = top left
plt.plot(x, x)
plt.subplot(2, 2, 2)  # 2 rows, 2 columns, 2nd subplot = top right
plt.plot(x, x**2)
plt.subplot(2, 1, 2)  # 2 rows, *1* column, 2nd subplot = bottom
plt.plot(x, x**3)
plt.show()

image7

Pylab vs Pyplot vs Matplotlib

There is some confusion around the relationship between pylab, pyplot and matplotlib. It's simple: matplotlib is the full library, it contains everything including pylab and pyplot.

Pyplot provides a number of tools to plot graphs, including the state-machine interface to the underlying object-oriented plotting library.

Pylab is a convenience module that imports matplotlib.pyplot and NumPy in a single name space. You will find many examples using pylab, but it is no longer recommended (because explicit imports are better than implicit ones).

Drawing text

You can call text to add text at any location in the graph. Just specify the horizontal and vertical coordinates and the text, and optionally some extra attributes

x = np.linspace(-1.4,1.4,25)
px = 1.0
py = px**2
plt.plot(x,x**2,'b-',px,py,'ro')
plt.text(0, 1.5, "Square function\n$y = x^2$", fontsize=20, color='blue', horizontalalignment="center")
plt.text(px - 0.08, py, "Beautiful point", ha="right", weight="heavy")
plt.text(px, py, "x = %0.2f\ny = %0.2f"%(px, py), rotation=50, color='gray')
# another method
plt.annotate("Beautiful point", xy=(px, py), xytext=(px-1.3,py+0.5),
                           color="green", weight="heavy", fontsize=14,
                           arrowprops={"facecolor": "lightgreen"})
plt.show()

Output:
image8

Legends

x = np.linspace(-1.4, 1.4, 50)
plt.plot(x, x**2, "r--", label="Square function")
plt.plot(x, x**3, "g-", label="Cube function")
plt.legend(loc="best")
plt.grid(True)
plt.show()

Output:
image9

Ticks and tickers

This example demonstrates how to customize ticks and tick labels on plots using Matplotlib. It generates three subplots, each with a different tick configuration.

x = np.linspace(-2, 2, 100)
Creates 100 evenly spaced points between -2 and 2 for plotting.
plt.figure(1, figsize=(15,10))

  1. Initializes a new figure window with ID 1.

figsize=(15,10) sets the figure size to 15 inches wide and 10 inches tall.

This preserves your original content while making it structured and easy to read in Markdown format. Let me know if you need any adjustments!

x = np.linspace(-2, 2, 100)

plt.figure(1, figsize=(15,10))
plt.subplot(131)
plt.plot(x, x**3)
plt.grid(True)
plt.title("Default ticks")

ax = plt.subplot(132)
plt.plot(x, x**3)
ax.xaxis.set_ticks(np.arange(-2, 2, 1))
plt.grid(True)
plt.title("Manual ticks on the x-axis")

ax = plt.subplot(133)
plt.plot(x, x**3)
plt.minorticks_on()
ax.tick_params(axis='x', which='minor', bottom='off')
ax.xaxis.set_ticks([-2, 0, 1, 2])
ax.yaxis.set_ticks(np.arange(-5, 5, 1))
ax.yaxis.set_ticklabels(["min", -4, -3, -2, -1, 0, 1, 2, 3, "max"])
plt.title("Manual ticks and tick labels\n(plus minor ticks) on the y-axis")


plt.grid(True)

plt.show()

Output:
image10

3D projection

from mpl_toolkits.mplot3d import Axes3D

x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)
X, Y = np.meshgrid(x, y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

figure = plt.figure(1, figsize = (12, 4))
subplot3d = plt.subplot(111, projection='3d')
surface = subplot3d.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=matplotlib.cm.coolwarm, linewidth=0.1)
plt.show()

Output:
image

plt.contourf(X, Y, Z, cmap=matplotlib.cm.coolwarm)
plt.colorbar()
plt.show()

Output:
image

Scatter plot

To draw a scatter plot, simply provide the x and y coordinates of the points.

from numpy.random import rand
x, y = rand(2, 100)
plt.scatter(x, y)
plt.show()

Output:
image

for color in ['red', 'green', 'blue']:
    n = 100
    x, y = rand(2, n)
    scale = 500.0 * rand(n) ** 5
    plt.scatter(x, y, s=scale, c=color, alpha=0.3, edgecolors='blue')

plt.grid(True)

plt.show()

Output:
image

Histogram

data = [1, 1.1, 1.8, 2, 2.1, 3.2, 3, 3, 3, 3]
plt.subplot(211)
plt.hist(data, bins = 10, rwidth=0.8)

plt.subplot(212)
plt.hist(data, bins = [1, 1.5, 2, 2.5, 3], rwidth=0.95)
plt.xlabel("Value")
plt.ylabel("Frequency")

plt.show()

Output:
image

data1 = np.random.randn(400)
data2 = np.random.randn(500) + 3
data3 = np.random.randn(450) + 6
data4a = np.random.randn(200) + 9
data4b = np.random.randn(100) + 10

plt.hist(data1, bins=5, color='g', alpha=0.75, label='bar hist') # default histtype='bar'
plt.hist(data2, color='b', alpha=0.65, histtype='stepfilled', label='stepfilled hist')
plt.hist(data3, color='r', histtype='step', label='step hist')
plt.hist((data4a, data4b), color=('r','m'), alpha=0.55, histtype='barstacked', label=('barstacked a', 'barstacked b'))

plt.xlabel("Value")
plt.ylabel("Frequency")
plt.legend()
plt.grid(True)
plt.show()

Output:
image

Thanks for Reading.....

7 Reactions

2 Bookmarks

Read next

_Ujjwal_

_Ujjwal_

Dec 14, 24

4 min read

|

Building an Own AI Chatbot: Integrating Custom Knowledge Bases

_Ujjwal_

_Ujjwal_

Dec 15, 24

9 min read

|

Exploratory data analysis with Pandas:Part 1