Quiz on AI Interviews Prep Live Training Corporate Training

Matplotlib Tutorials.

1. What is Matplotlib?

Matplotlib is a popular Python library used for data visualization. It helps us create graphs, charts, and plots to understand data easily.

2. Installing Matplotlib

Use the following command to install Matplotlib:

pip install matplotlib

3. Importing Matplotlib

The most common way to import Matplotlib is:

import matplotlib.pyplot as plt

4. Line Plot

A line plot shows trends over time.


import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

plt.plot(x, y)
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.title("Simple Line Plot")
plt.show()
    

5. Bar Chart

Bar charts are used to compare different categories.


import matplotlib.pyplot as plt

subjects = ['Math', 'Science', 'English']
marks = [85, 90, 78]

plt.bar(subjects, marks)
plt.title("Student Marks")
plt.xlabel("Subjects")
plt.ylabel("Marks")
plt.show()
    

6. Pie Chart

Pie charts show parts of a whole.


import matplotlib.pyplot as plt

sizes = [40, 30, 20, 10]
labels = ['A', 'B', 'C', 'D']

plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.title("Pie Chart Example")
plt.show()
    

7. Scatter Plot

Scatter plots show the relationship between two variables.


import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [5, 7, 4, 8, 6]

plt.scatter(x, y)
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.title("Scatter Plot")
plt.show()
    

8. Adding Colors and Styles


plt.plot(x, y, color='red', linestyle='--', marker='o')
    
  • color – changes line color
  • linestyle – dashed, dotted, etc.
  • marker – marks data points

9. Saving a Plot

You can save a graph as an image file.


plt.savefig("graph.png")
    

10. Applications of Matplotlib

  • Data analysis
  • Machine learning visualization
  • Scientific research
  • Business reports