Plot the dataset to display Horizontal Trend – Python Pandas

A horizontal trend (also called stationary trend) represents data that fluctuates around a constant mean over time without showing clear upward or downward movement. In this tutorial, we'll learn how to plot a dataset with a horizontal trend using Pandas and Matplotlib.

Required Libraries

First, import the necessary libraries for data manipulation and visualization ?

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

Creating Sample Data with Horizontal Trend

Let's create sample sales data that exhibits a horizontal trend pattern ?

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# Create sample data with horizontal trend
np.random.seed(42)
dates = pd.date_range('2023-01-01', periods=100, freq='D')
sales = 1000 + np.random.normal(0, 50, 100)  # Mean around 1000 with random fluctuation

# Create DataFrame
data = {'Sold_On': dates, 'Sales': sales}
dataFrame = pd.DataFrame(data)

print("Sample DataFrame:")
print(dataFrame.head())
Sample DataFrame:
    Sold_On        Sales
0 2023-01-01  1074.826146
1 2023-01-02   997.177022
2 2023-01-03  1097.738041
3 2023-01-04  1120.736628
4 2023-01-05   986.370492

Converting Date Column and Setting Index

Convert the date column to datetime type and set it as the index for proper time series plotting ?

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# Create sample data
np.random.seed(42)
dates = pd.date_range('2023-01-01', periods=100, freq='D')
sales = 1000 + np.random.normal(0, 50, 100)

dataFrame = pd.DataFrame({'Sold_On': dates, 'Sales': sales})

# Convert to datetime and set as index
dataFrame['Sold_On'] = pd.to_datetime(dataFrame['Sold_On'])
dataFrame = dataFrame.set_index('Sold_On')

print("DataFrame with datetime index:")
print(dataFrame.head())
DataFrame with datetime index:
                Sales
Sold_On              
2023-01-01  1074.826146
2023-01-02   997.177022
2023-01-03  1097.738041
2023-01-04  1120.736628
2023-01-05   986.370492

Plotting the Horizontal Trend

Create the plot to visualize the horizontal trend in the data ?

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# Create sample data with horizontal trend
np.random.seed(42)
dates = pd.date_range('2023-01-01', periods=100, freq='D')
sales = 1000 + np.random.normal(0, 50, 100)

dataFrame = pd.DataFrame({'Sold_On': dates, 'Sales': sales})
dataFrame['Sold_On'] = pd.to_datetime(dataFrame['Sold_On'])
dataFrame = dataFrame.set_index('Sold_On')

# Create the plot
plt.figure(figsize=(12, 6))
dataFrame.plot(title='Sales Data - Horizontal Trend', 
               xlabel='Date', ylabel='Sales Amount')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
[This displays a line plot showing sales data fluctuating around 1000 with no clear upward or downward trend over time]

Adding Trend Line for Analysis

To better visualize the horizontal nature, add a horizontal line showing the mean value ?

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# Create sample data
np.random.seed(42)
dates = pd.date_range('2023-01-01', periods=100, freq='D')
sales = 1000 + np.random.normal(0, 50, 100)

dataFrame = pd.DataFrame({'Sold_On': dates, 'Sales': sales})
dataFrame['Sold_On'] = pd.to_datetime(dataFrame['Sold_On'])
dataFrame = dataFrame.set_index('Sold_On')

# Create plot with mean line
plt.figure(figsize=(12, 6))
dataFrame.plot(label='Sales Data')
plt.axhline(y=dataFrame['Sales'].mean(), color='red', 
            linestyle='--', label=f'Mean: {dataFrame["Sales"].mean():.2f}')
plt.title('Sales Data with Horizontal Trend')
plt.xlabel('Date')
plt.ylabel('Sales Amount')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()

print(f"Mean sales value: {dataFrame['Sales'].mean():.2f}")
print(f"Standard deviation: {dataFrame['Sales'].std():.2f}")
Mean sales value: 1008.37
Standard deviation: 47.58
[This displays a plot with sales data fluctuating around the mean line, clearly showing horizontal trend]

Key Characteristics of Horizontal Trends

Characteristic Description
Mean Remains relatively constant over time
Variance Consistent fluctuation around the mean
Direction No clear upward or downward movement
Stationarity Statistical properties remain constant

Conclusion

Horizontal trends represent stationary data that fluctuates around a constant mean without directional movement. Use Pandas' plot() method with datetime indexing to visualize these patterns effectively. Adding mean lines helps identify the horizontal nature of the trend.

---
Updated on: 2026-03-26T13:42:22+05:30

414 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements