How to draw rounded line ends using Matplotlib?

To draw rounded line ends using Matplotlib, we can use the solid_capstyle='round' parameter. This creates smooth, circular ends instead of the default square line caps, making your plots more visually appealing.

Basic Rounded Line Example

Let's start with a simple example showing the difference between default and rounded line caps ?

import matplotlib.pyplot as plt
import numpy as np

# Create sample data
x = np.linspace(0, 10, 5)
y = np.sin(x)

# Create the plot
fig, ax = plt.subplots(figsize=(8, 4))

# Plot with rounded line ends
ax.plot(x, y, linewidth=10, solid_capstyle='round', color='red', label='Rounded caps')

# Add labels and show
ax.set_title('Line with Rounded Ends')
ax.legend()
plt.show()

Comparing Different Cap Styles

Matplotlib offers three cap styles: 'butt' (default), 'round', and 'projecting'. Here's how they compare ?

import matplotlib.pyplot as plt
import numpy as np

# Create sample data
x = [1, 3]
y_positions = [3, 2, 1]
cap_styles = ['butt', 'round', 'projecting']
colors = ['blue', 'red', 'green']

fig, ax = plt.subplots(figsize=(8, 5))

# Plot lines with different cap styles
for i, (cap_style, color) in enumerate(zip(cap_styles, colors)):
    ax.plot(x, [y_positions[i], y_positions[i]], 
            linewidth=15, solid_capstyle=cap_style, 
            color=color, label=f'{cap_style} caps')

ax.set_xlim(0.5, 3.5)
ax.set_ylim(0.5, 3.5)
ax.set_title('Comparison of Line Cap Styles')
ax.legend()
ax.grid(True, alpha=0.3)
plt.show()

Advanced Usage with Multiple Lines

You can apply rounded caps to multiple lines in the same plot for consistent styling ?

import matplotlib.pyplot as plt
import numpy as np

# Generate multiple datasets
x = np.linspace(0, 2*np.pi, 10)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.sin(x + np.pi/4)

fig, ax = plt.subplots(figsize=(10, 6))

# Plot multiple lines with rounded caps
ax.plot(x, y1, linewidth=8, solid_capstyle='round', color='red', alpha=0.7, label='sin(x)')
ax.plot(x, y2, linewidth=8, solid_capstyle='round', color='blue', alpha=0.7, label='cos(x)')
ax.plot(x, y3, linewidth=8, solid_capstyle='round', color='green', alpha=0.7, label='sin(x+?/4)')

ax.set_title('Multiple Lines with Rounded Caps')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend()
ax.grid(True, alpha=0.3)
plt.show()

Key Parameters

Parameter Values Description
solid_capstyle 'butt', 'round', 'projecting' Controls the style of line ends
linewidth Number (e.g., 1, 5, 10) Thickness of the line (effect more visible with thicker lines)
dash_capstyle 'butt', 'round', 'projecting' Controls cap style for dashed lines

Conclusion

Using solid_capstyle='round' creates smooth, professional-looking line ends in your Matplotlib plots. The effect is most noticeable with thicker lines and works well for creating clean, modern visualizations.

Updated on: 2026-03-25T23:51:20+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements