Basic Line Plot

Create a simple line plot:

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

plt.plot(x, y)
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.title('Simple Line Plot')
plt.show()

Multiple Lines

Plot multiple lines on same graph:

x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [2, 4, 8, 16, 32]

plt.plot(x, y1, label='Squares')
plt.plot(x, y2, label='Powers of 2')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Multiple Lines')
plt.legend()
plt.show()

Customizing Lines

Customize line appearance:

plt.plot(x, y,
         color='blue',        # Line color
         linestyle='--',      # Line style: -, --, -., :
         linewidth=2,         # Line width
         marker='o',          # Marker: o, s, ^, etc.
         markersize=8,        # Marker size
         markerfacecolor='red',  # Marker fill color
         markeredgecolor='black', # Marker edge color
         label='Data')        # Legend label

Line Styles

Different line styles:

plt.plot(x, y, linestyle='-')    # Solid line
plt.plot(x, y, linestyle='--')   # Dashed
plt.plot(x, y, linestyle='-.')   # Dash-dot
plt.plot(x, y, linestyle=':')    # Dotted

# Or use shorthand
plt.plot(x, y, '-')   # Solid
plt.plot(x, y, '--')  # Dashed
plt.plot(x, y, '-.')  # Dash-dot
plt.plot(x, y, ':')   # Dotted

Markers

Different marker styles:

plt.plot(x, y, marker='o')    # Circle
plt.plot(x, y, marker='s')    # Square
plt.plot(x, y, marker='^')    # Triangle up
plt.plot(x, y, marker='*')    # Star
plt.plot(x, y, marker='x')    # X
plt.plot(x, y, marker='+')    # Plus

Plotting from NumPy Arrays

Use NumPy arrays for smooth curves:

import numpy as np

x = np.linspace(0, 10, 100)  # 100 points from 0 to 10
y = np.sin(x)

plt.plot(x, y)
plt.xlabel('X')
plt.ylabel('sin(X)')
plt.title('Sine Wave')
plt.grid(True)
plt.show()

Subplots

Create multiple plots:

fig, axes = plt.subplots(2, 1, figsize=(8, 6))

# First subplot
axes[0].plot(x, y1)
axes[0].set_title('Plot 1')

# Second subplot
axes[1].plot(x, y2)
axes[1].set_title('Plot 2')

plt.tight_layout()
plt.show()

Best Practices

  • Add labels: Always label axes and add title
  • Use legends: When plotting multiple lines
  • Choose appropriate markers: For discrete data
  • Use grid: Makes reading values easier
  • Set figure size: For better visibility

Next Steps

Learn about bar charts or scatter plots for other visualization types.