Menu

Time Series
Static
51 Python scripts generated for line graph this week

Line Graph

Chart overview

Line graphs are fundamental visualizations for displaying continuous data and trends over time.

Key points

  • By connecting data points with lines, they effectively communicate the direction and rate of change in your data.
  • Multiple lines can be used to compare trends across different categories, making line graphs ideal for stock prices, temperature changes, sales trends, and any time-series analysis.

Python Tutorial

How to create a line graph in Python

Use the full tutorial for implementation details, troubleshooting, and chart variations in matplotlib, seaborn, and plotly.

How to Plot Time Series Data in Python

Example Visualization

Multi-line graph showing temperature trends for 3 cities over a year

Create This Chart Now

Generate publication-ready line graphs with AI in seconds. No coding required – just describe your data and let AI do the work.

View example prompt
Example AI Prompt

"Create a multi-line graph comparing 'Monthly Average Temperature' for 3 cities (New York, Miami, Chicago) over a full year (Jan-Dec). Generate realistic data: New York (30°F-85°F), Miami (65°F-90°F), Chicago (25°F-80°F) with appropriate seasonal patterns. Use distinct line colors (NYC: blue, Miami: orange, Chicago: green) and marker styles (circle, square, diamond). Add a shaded region showing the 'comfortable range' (60-75°F). Include grid lines, format Y-axis with °F, add month abbreviations on X-axis. Title the chart professionally, add a legend positioned outside the plot, and annotate the hottest and coldest points for each city."

How to create this chart in 30 seconds

1

Upload Data

Drag & drop your Excel or CSV file. Plotivy securely processes it in your browser.

2

AI Generation

Our AI analyzes your data and generates the Line Graph code automatically.

3

Customize & Export

Tweak the design with natural language, then export as high-res PNG, SVG or PDF.

Newsletter

Get one weekly tip for better line graphs

Join researchers receiving concise Python plotting techniques to improve chart clarity and reduce revision cycles.

No spam. Unsubscribe anytime.

Python Code Example

example.py
# === IMPORTS ===
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime

# === USER-EDITABLE PARAMETERS ===
x_col = 'Date'          # Change: column name for x-axis (datetime)
y_col = 'Temperature'   # Change: column name for y-axis (numeric)
group_col = 'City'      # Change: column name for grouping variable
figsize = (12, 6)       # Change: figure size in inches
title_fontsize = 18     # Change: title font size
label_fontsize = 16     # Change: axis label and tick font size
colors = ['#1f77b4', '#ff7f0e', '#2ca02c']  # Change: hex colors for each city
markers = ['o', 's', '^']  # Change: markers for each city
line_width = 2          # Change: line width
show_legend = True      # Change: whether to show legend

# === DATA PREPARATION ===
# Generate example dataset: monthly average temperatures for 3 cities over one year
np.random.seed(0)
months = pd.date_range(start='2023-01-01', periods=12, freq='MS')
cities = ['City A', 'City B', 'City C']
data = []

for city in cities:
    if city == 'City A':
        base = 20
        trend = 5
    elif city == 'City B':
        base = 15
        trend = 3
    else:  # City C
        base = 10
        trend = 1
    temps = base + trend * np.sin(np.linspace(0, 2*np.pi, 12)) + np.random.normal(0, 2, 12)
    for date, temp in zip(months, temps):
        data.append({'Date': date, 'City': city, 'Temperature': temp})

df = pd.DataFrame(data)

# === ANALYSIS ===
# Compute max temperature per city
max_temps = df.groupby(group_col)[y_col].max()
max_months = df.loc[df.groupby(group_col)[y_col].idxmax()][['Date', group_col, y_col]]
mean_temps = df.groupby(group_col)[y_col].mean()

# Print analysis results
print("Maximum temperatures per city:")
for city in cities:
    month_str = max_months.loc[max_months[group_col]==city, 'Date'].dt.strftime('%b %Y').values[0]
    print(f"  {city}: {max_temps[city]:.1f}°C on {month_str}")
print("\nMean temperatures per city:")
for city in cities:
    print(f"  {city}: {mean_temps[city]:.1f}°C")

# Determine city with highest max temperature for title
top_city = max_temps.idxmax()
top_temp = max_temps[top_city]
top_month = max_months.loc[max_months[group_col]==top_city, 'Date'].dt.strftime('%b').values[0]

# === PLOT CREATION ===
fig, ax = plt.subplots(figsize=figsize)

# Plot each city's temperature trend
for i, city in enumerate(cities):
    city_data = df[df[group_col]==city].sort_values(x_col)
    ax.plot(city_data[x_col], city_data[y_col],
            label=city,
            color=colors[i],
            marker=markers[i],
            linewidth=line_width,
            markersize=6)

# Formatting
ax.set_title(f"{top_city} reaches highest temperatures of {top_temp:.1f}°C in {top_month}",
             fontsize=title_fontsize)
ax.set_xlabel('Month', fontsize=label_fontsize)
ax.set_ylabel('Temperature (°C)', fontsize=label_fontsize)
ax.tick_params(axis='both', which='major', labelsize=label_fontsize)

# Legend
if show_legend:
    ax.legend(loc='upper left', fontsize=label_fontsize)

# Annotation of max temperatures
max_temps_str = ', '.join([f"{city}: {max_temps[city]:.1f}°C" for city in cities])
ax.text(0.95, 0.85, f"Max temps: {max_temps_str}",
        transform=ax.transAxes,
        ha='right', va='top',
        bbox=dict(boxstyle='round', facecolor='white', alpha=0.8))

# Layout adjustments
plt.subplots_adjust(top=0.90, bottom=0.12, left=0.12, right=0.95)
plt.tight_layout()

# Display plot
plt.show()
# END-OF-CODE

Opens the Analyze page with this code pre-loaded and ready to execute

Console Output

Output
Annual Temperature Statistics:
New York: min=30°F, max=82°F, avg=54.6°F
Miami: min=65°F, max=90°F, avg=79.8°F
Chicago: min=25°F, max=80°F, avg=52.3°F

Comfortable Months (60-75°F): NYC=7, Miami=4, Chicago=5

Common Use Cases

  • 1Stock price tracking over time
  • 2Website traffic analysis
  • 3Temperature and weather trends
  • 4Sales performance comparison

Pro Tips

Use distinct colors and markers for multiple series

Consider adding a legend outside the plot area

Highlight important data points or events

Long-tail keyword opportunities

time series plot python
matplotlib date axis formatting
line plot with rolling average python
plotly interactive time series

High-intent chart variations

Line Graph with confidence interval overlays
Line Graph optimized for publication layouts
Line Graph with category-specific color encoding
Interactive Line Graph for exploratory analysis

Library comparison for this chart

matplotlib

Best when you need full control over axis formatting, annotation placement, and journal-specific styling for line-graph.

seaborn

Fastest path to statistically-aware defaults and tidy-data workflows, especially for grouped and distribution-focused line-graph views.

plotly

Best for interactive hover, zoom, and web sharing when collaborators need to inspect values directly from line-graph figures.

Free Cheat Sheet

Scientific Chart Selection Cheat Sheet

Not sure whether to use a Violin Plot, Box Plot, or Ridge Plot? Download our single-page reference mapping the most-used scientific chart types, exactly when to use them, and the core Matplotlib/Seaborn functions.

Comparison Charts
Distribution Charts
Time Series Data
Common Mistakes
No spam. Unsubscribe anytime.