Back to Python
2026-04-095 min read

DS Plotting Functions (Python Programming)

Learn DS Plotting Functions (Python Programming) step by step with clear examples and exercises.

Title: Data Science Plotting Linear Functions (Python Programming)

Why This Matters

Data science is a field that revolves around extracting insights from data using various techniques. One of the key aspects of data science is visualization, which helps us understand patterns and trends in the data. In this lesson, we will learn how to plot linear functions using Python, a popular programming language for data analysis. This skill is essential for data scientists, as it allows them to present their findings in an easily understandable format.

Linear functions are fundamental in mathematics and have numerous applications in real-world scenarios such as physics, economics, and engineering. By plotting linear functions, we can visualize the relationship between two variables and make predictions based on the slope and intercept of the line.

Prerequisites

Before diving into plotting linear functions, you should have a basic understanding of the following:

  1. Python programming: Familiarity with Python syntax, variables, and data structures such as lists and dictionaries.
  2. Matplotlib library: Knowledge of how to install and import the Matplotlib library in Python.
  3. Linear algebra: Understanding of linear equations and their graphical representation. It is recommended to have a good grasp of basic algebra concepts, including functions, slopes, and intercepts.
  4. Familiarity with Jupyter Notebook or similar environment for running and executing Python code.

Core Concept

Matplotlib is a powerful plotting library in Python that provides an object-oriented API for creating various types of plots. In this lesson, we will focus on line plots, which are useful for visualizing linear functions.

To create a line plot of a linear function, we will use the plot() function from Matplotlib's pyplot module. The general syntax for creating a line plot is as follows:

import matplotlib.pyplot as plt

x = list(range(10)) # Create x-values
y = [2 * i for i in x] # Create y-values using linear function y = 2x
plt.plot(x, y) # Plot the line
plt.show() # Display the plot

In this example, we first import the Matplotlib library and create two lists for our x and y values. The x-values are simply a range of 10 integers, while the y-values are calculated using the linear function y = 2x. We then call the plot() function to plot the line, passing in our x and y data as arguments. Finally, we use plt.show() to display the plot.

The slope of the line can be adjusted by modifying the coefficient of the independent variable (x) in the linear function. For example, if we want to create a line plot for the linear function y = 3x + 2, we would change the y-values calculation as follows:

y = [3 * i + 2 for i in x]

Worked Example

Let's create a line plot for the linear function y = 3x + 2:

import matplotlib.pyplot as plt

x = list(range(10))
y = [3 * i + 2 for i in x]
plt.plot(x, y)
plt.show()

When you run this code, Matplotlib will create a line plot of the function y = 3x + 2 over the range of 10 points. The resulting plot should look like this:

!Linear Function Plot

Common Mistakes

  1. Forgetting to import Matplotlib: Make sure you have imported the matplotlib.pyplot module at the beginning of your script.
  2. Incorrect x and y values: Ensure that your x-values are a list or array, and that your y-values are calculated correctly based on the linear function.
  3. Not calling plt.show(): Remember to display the plot using plt.show() after creating it with plt.plot().
  4. Plotting multiple lines without separating them: If you want to plot multiple lines on the same graph, make sure to call plt.plot() for each line and use different colors or labels to distinguish between them.
  5. Not specifying a label for x and y axes: To make your plots more informative, always include labels for both x and y axes. This can be done using the xlabel() and ylabel() functions from Matplotlib's pyplot module.
  6. Not setting a title for the plot: A title helps to provide context and make your plots more readable. You can set a title for your plot using the title() function from Matplotlib's pyplot module.
  7. Not saving your plot: If you want to save your plot as an image file, use the savefig() function from Matplotlib's pyplot module. For example, to save the current plot as a PNG image named "my_plot.png", you can use the following code:
plt.savefig("my_plot.png")

Practice Questions

  1. Write a Python script to create a line plot of the linear function y = 4x - 5 over the range of 20 points.
  2. Modify the previous example to add a second line for the function y = -x + 3, and label both lines on the plot. Include labels for x and y axes and set a title for the plot.
  3. Create a scatter plot of the data [(1, 2), (2, 4), (3, 6), (4, 8)], which represents a linear relationship between x and y. Then, add a best-fit line to the scatter plot using the polyfit() function from Matplotlib's polynomial module.
  4. Create a line plot for the quadratic function y = x^2 + 3x - 2 over the range of -5 to 5. Calculate the roots (zeroes) of this quadratic function and mark them on the plot using different marker styles.

FAQ

Q: How can I customize the appearance of my plot?

A: You can customize various aspects of your plot, such as axis labels, title, line color, and marker style, using functions like plt.xlabel(), plt.ylabel(), plt.title(), plt.plot(color=), and plt.scatter(marker=).

Q: How do I save my plot as an image file?

A: To save your plot as an image file, use the savefig() function from Matplotlib's pyplot module. For example, to save the current plot as a PNG image named "my_plot.png", you can use the following code:

plt.savefig("my_plot.png")

Q: How do I add gridlines to my plot?

A: You can add gridlines to your plot using the grid() function from Matplotlib's pyplot module. To customize the appearance of the grid, you can use the tick_params() function. For example, to set both major and minor gridlines with dashed lines, you can use the following code:

plt.grid(which="major", linestyle="-.")
plt.grid(which="minor", linestyle=":")

Q: How do I add a legend to my plot?

A: You can add a legend to your plot using the legend() function from Matplotlib's pyplot module. To create a legend that includes line labels, you can pass in a list of labels as an argument to the legend() function. For example:

plt.plot(x, y1, label="y = 3x + 2")
plt.plot(x, y2, label="y = -x + 3")
plt.legend()

This will create a legend that includes two lines, one for each plot, with the labels "y = 3x + 2" and "y = -x + 3".

DS Plotting Functions (Python Programming) | Python | XQA Learn