How to Create a Line Chart in Python?

Estimated read time 2 min read

To create a line chart in Python, you can use the matplotlib library, which provides a wide range of tools for creating different types of plots. Here’s how you can create a simple line chart:

import matplotlib.pyplot as plt

# Define your data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Create a figure and axis object
fig, ax = plt.subplots()

# Plot the data as a line
ax.plot(x, y)

# Add labels and title
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_title('Line Chart')

# Show the plot

In the code above, we first import the matplotlib.pyplot module as plt. We then define our data as two lists, x and y, with five values each.

Next, we create a figure and axis object using the subplots() function, which returns a tuple containing the figure and axis objects. We store these objects in the variables fig and ax, respectively.

We then use the plot() method of the axis object to plot the data as a line. We pass the x and y lists as arguments to plot().

Finally, we use the set_xlabel(), set_ylabel(), and set_title() methods of the axis object to add labels and a title to the plot. We then call to display the plot.

This will create a simple line chart with the values of x on the x-axis and the values of y on the y-axis. The line chart will have a label for the x-axis, a label for the y-axis, and a title.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply