Back to Python Notes
Topic #268

Plotting

By the end of this lesson, you will be able to create a basic line chart using Python's Matplotlib library to visualize trends in numerical data.

What it is

Plotting in Python typically refers to creating visual representations of data. The most common library for this is matplotlib.pyplot. A line chart connects individual data points with straight lines, making it ideal for showing how a variable changes over time or across an ordered sequence. Key concepts include the x-axis (independent variable), y-axis (dependent variable), and the plot object which holds the graphical elements.

Why it matters

  • Trend Identification: Quickly spot increases, decreases, or patterns in time-series data like stock prices or temperature.
  • Data Comparison: Overlay multiple lines on one chart to compare different datasets side-by-side.
  • Communication: Visuals are often more intuitive than raw tables for stakeholders who need quick insights.
  • Debugging: Plotting intermediate results helps verify that your calculations behave as expected during development.

Syntax or steps

The standard workflow involves importing the library, preparing data, calling the plot function, adding labels, and displaying the result.

  1. Import matplotlib.pyplot.
  2. Create lists or arrays for x and y values.
  3. Call plt.plot(x, y) to draw the line.
  4. Add context with plt.xlabel(), plt.ylabel(), and plt.title().
  5. Show the graph with plt.show().

Example

import matplotlib.pyplot as plt

# Sample data: Months and Sales figures
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
sales = [150, 200, 180, 250, 300]

# Create the line chart
plt.plot(months, sales)

# Add labels and title
plt.xlabel('Month')
plt.ylabel('Sales (Units)')
plt.title('Monthly Sales Trend')

# Display the plot
plt.show()

Explanation: We import pyplot as plt. Two lists, months and sales, hold our categorical x-data and numerical y-data. plt.plot() draws the line connecting these points. Labels clarify what each axis represents, and plt.show() renders the window containing the chart.

Common mistakes

  • Forgetting plt.show(): Without this call, the script runs but no window appears (especially in scripts vs. notebooks).
  • Mismatched lengths: If x and y lists have different numbers of items, Matplotlib raises a ValueError.
  • Overwriting plots: Calling plt.plot() again without clearing the figure adds to the current plot. Use plt.clf() to clear if starting fresh.
  • Ignoring scale: Large differences in y-values can make smaller variations invisible; consider log scales or separate charts if needed.

When to use it

Line charts are best for continuous data or ordered categories. Compare them with bar charts for discrete comparisons.

Chart TypeBest ForExample Data
Line ChartTrends over time/sequenceTemperature per hour
Bar ChartComparing distinct categoriesSales by product type
Scatter PlotCorrelation between two variablesHeight vs. Weight

Practice

Guided Exercise: Modify the example above to add a second line representing "Expenses" with values [100, 120, 110, 140, 160]. Ensure both lines appear on the same chart.

Challenge: Change the color of the first line to red and the second to blue using the color parameter in plt.plot().

Hint: Call plt.plot() twice before calling plt.show(). Example: plt.plot(months, sales, color='red').

Quick check

Question: What happens if you omit plt.show() when running a Python script?

Answer: The code executes without error, but the plot window does not appear because the display command was never triggered.

Summary

Matplotlib’s plt.plot() provides a simple yet powerful way to visualize trends. By pairing data lists with labeling functions, you transform raw numbers into actionable insights. Mastering this basic pattern is the foundation for more complex data visualization tasks.

Want to go beyond the notes?

Join Coding Now Tech Institute's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Plotting – FAQs

Quick answers about learning Plotting in Python.

This free note from Coding Now Tech Institute explains Plotting in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on Coding Now Tech Institute, including Plotting, is 100% free with no signup required.
With focused practice, most students grasp Plotting in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now