Movatterモバイル変換


[0]ホーム

URL:


Python Pandas Tutorial

Python Pandas - Line Plot



A line plot is a visual representation of data where individual points are connected by straight lines. It is mainly used to observe relationships between two variables on x-axis and y-axis.

This plot helps you to visualize fluctuations, patterns, trends, or progressions in your data. For instance, let us create a graph where you have the student attendance over a specific period, such as months or semesters. The x-axis will represent the months, and the y-axis will represent the attendance in percent sign −

Line Plot Introduction

In this tutorial, we will learn how to create and customize line plots using the Pandas library in Python.

Line Plot in Pandas

Pandas provides theplot.line() method to create line plots from Series and DataFrames. This method internally uses Matplotlib and returns amatplotlib.axes.Axes object or an NumPy arraynp.ndarray of Axes when subplots parameter is set to True.

  • DataFrame.plot.line(): Creates line plot for one or more columns in a DataFrame.

  • Series.plot.line(): Creates a line plot for a single Series.

Syntax

The following is the syntax of the plot.line() method for both the Series and DataFrames objects −

DataFrame.plot.line(x=None, y=None, **kwargs)

Parameters,

  • x: The column label or index position to be plotted on the x-axis. If not specified, the DataFrame index is used.

  • y: The column label or index position to be plotted on the y-axis. If not specified, all numerical columns are used.

  • **kwargs: Additional keyword arguments to customize the plot appearance.

Example: Creating Line Plot for Series Data

This example demonstrates using theSeries.plot.line() method on a Pandas Series object.

import pandas as pdimport numpy as npimport matplotlib.pyplot as plt# Create a Pandas Seriesseries = pd.Series(3 * np.random.rand(4), index=["a", "b", "c", "d"])# Generate a line plotseries.plot.line(figsize=(7, 4))# Set title and Display the plotplt.title('Basic line Plot')plt.show()

Following is the output of the above code −

Basic line Plot

Example: Creating Line Plot for a DataFrame

This example demonstrates how to create a line plot for multiple columns in a DataFrame using theDataFrame.plot.line() method.

import pandas as pdimport matplotlib.pyplot as plt# Create a DataFrame with population datadf = pd.DataFrame({    'Pig': [20, 18, 489, 675, 1776],    'Horse': [4, 25, 281, 600, 1900]}, index=[1990, 1997, 2003, 2009, 2014])# Generate a line plotdf.plot.line()# Show the plotplt.title('Animal Population Over Time')plt.xlabel('Year')plt.ylabel('Population')plt.show()

After executing the above code, we get the following output −

line Plot for DataFrame

Customizing a Line Plot

Pandas allows customization of line plots through various parameters such as, labels, colors, autopct, fontsize, and more.

Example

This example demonstrates customizing the line plot using the addition keyword arguments. Here we will create the separate subplots by setting thesubplots=True and specified the different colors for each column using thecolor parameter.

import pandas as pdimport matplotlib.pyplot as plt# Create a DataFrame with population datadf = pd.DataFrame({    'Pig': [20, 18, 489, 675, 1776],    'Horse': [4, 25, 281, 600, 1900]}, index=[1990, 1997, 2003, 2009, 2014])# Customizing line colorsdf.plot.line(subplots=True, color={"Pig": "pink", "Horse": "brown"})# Show the plotplt.title('Animal Population Over Time')plt.xlabel('Year')plt.ylabel('Population')plt.show()

Following is the output of the above code −

Customizing a line Plot

Line Plot One Column Against Another

Pandasplot.line() method easily draw line plot one column against another column by specifying.

Example

This example demonstrates how to plot one column against another using theplot.line() method.

import pandas as pdimport matplotlib.pyplot as plt# Create a DataFrame with population datadf = pd.DataFrame({    'Pig': [20, 18, 489, 675, 1776],    'Horse': [4, 25, 281, 600, 1900]}, index=[1990, 1997, 2003, 2009, 2014])# Plotting Horse population against Pig populationdf.plot.line(x='Pig', y='Horse')# Show the plotplt.title('Horse Population vs Pig Population')plt.xlabel('Pig Population')plt.ylabel('Horse Population')plt.show()

On executing the above code we will get the following output −

line Plot Against Another Column
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp