Menu

Matplotlib

What is Matplotlib?

- Matplotlib is a Python plotting library used for creating static, animated, and interactive visualizations.
- It can be used for plotting graphs such as line plots, bar charts, histograms, and more.
- Matplotlib was created by John D. Hunter in 2003 and has become a core plotting library in Python.
- Matplotlib works well with NumPy and Pandas data structures.

At First we downlode the library of Matplotlib

pip install matplotlib

Matplotlib Basic Example

import matplotlib.pyplot as plt

# Create data
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]

# Create a figure
plt.figure(figsize=(10, 6))

# Plot the data
plt.plot(x, y, label='y = x^2')

# Set title, labels, and limits
plt.title('Basic Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.xlim(0, 6)
plt.ylim(0, 30)

# Add ticks
plt.xticks([1, 2, 3, 4, 5])
plt.yticks([0, 5, 10, 15, 20, 25])

# Add grid, legend, and show the plot
plt.grid(True)
plt.legend()
plt.show()

This code demonstrates how to use various `matplotlib` functions:

  • plt.figure(figsize=(10, 6)) - Initializes a new figure with a custom size (width: 10, height: 6).
  • plt.plot(x, y, label='y = x^2') - Plots the line for the data and adds a label for the legend.
  • plt.title('Basic Plot') - Sets the title of the plot.
  • plt.xlabel('X-axis') and plt.ylabel('Y-axis') - Sets labels for the X and Y axes respectively.
  • plt.xlim(0, 6) and plt.ylim(0, 30) - Defines the limits for the X and Y axes.
  • plt.xticks([1, 2, 3, 4, 5]) and plt.yticks([0, 5, 10, 15, 20, 25]) - Specifies the tick positions for the X and Y axes.
  • plt.grid(True) - Displays the grid on the plot.
  • plt.legend() - Adds a legend to the plot.
  • plt.show() - Displays the plot in a window.

Conclusion

Matplotlib is a very versatile plotting library that can be used for a variety of visualizations. It is essential for data visualization in Python and can be customized to meet specific needs, including adding titles, labels, legends, and modifying axes and grid properties.

Need Help?

If any problem occurs, feel free to contact me for assistance.

Leave a Comment

Comments

    No comments yet. Be the first to comment!