杰瑞科技汇

Python linestyles有哪些常用样式?

Of course! In Python, when you're working with data visualization libraries like Matplotlib and Seaborn, "linestyles" refer to the pattern used to draw a line connecting data points. This is a crucial element for distinguishing between different lines in a plot, especially when colors are similar or when you're printing in black and white.

Python linestyles有哪些常用样式?-图1
(图片来源网络,侵删)

Here's a comprehensive guide to using linestyles in Python, primarily focusing on Matplotlib, which is the foundation for many other libraries.


The Core Concept: linestyle or ls

The primary parameter you'll use to control a line's style is linestyle. It has a short alias, ls, which is very common.

Basic Solid, Dashed, and Dotted Lines

You can specify linestyles in a few ways:

  • Using a string code (most common):

    Python linestyles有哪些常用样式?-图2
    (图片来源网络,侵删)
    • or 'solid': Solid line (default)
    • or 'dashed': Dashed line
    • or 'dotted': Dotted line
    • or 'dashdot': Dash-dot line
  • Using a tuple of (offset, (on, off, on, off, ...)):

    • This gives you full control over the dash pattern. offset is where the dash pattern starts, and the tuple defines the sequence of dashes and gaps.
    • Example: (0, (5, 5)) is the same as .
    • Example: (0, (1, 1)) is the same as .
    • Example: (0, (10, 5, 3, 5)) creates a custom dash pattern.

Example: Basic Linestyles

import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.linspace(0, 10, 100)
y_sin = np.sin(x)
y_cos = np.cos(x)
# Create a figure and axis
fig, ax = plt.subplots(figsize=(10, 6))
# Plot with different linestyles
ax.plot(x, y_sin, linestyle='--', label='Sine (Dashed)')
ax.plot(x, y_cos, linestyle=':', label='Cosine (Dotted)')
# You can also use the short alias 'ls'
# ax.plot(x, y_sin, ls='--', label='Sine (Dashed)')
# Add labels and legend
ax.set_title("Basic Linestyles in Matplotlib")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.legend()
ax.grid(True)
plt.show()

Output:


Combining Line Style and Color

You can easily combine linestyle with color to make your plots even more informative. The most common way is to pass both as arguments to the plot() function.

  • color (or c): Specifies the color (e.g., 'red', 'b', '#FF5733').
  • linestyle (or ls): Specifies the line pattern.
  • linewidth (or lw): Specifies the thickness of the line.

Example: Combining Style and Color

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.sin(x - 1)
y3 = np.sin(x - 2)
fig, ax = plt.subplots(figsize=(10, 6))
# Combine linestyle, color, and linewidth
ax.plot(x, y1, linestyle='-', color='blue', linewidth=2, label='Solid Blue')
ax.plot(x, y2, linestyle='--', color='red', linewidth=2, label='Dashed Red')
ax.plot(x, y3, linestyle=':', color='green', linewidth=2, label='Dotted Green')
ax.set_title("Combining Linestyle, Color, and Linewidth")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.legend()
ax.grid(True)
plt.show()

Output:


Custom Dash Patterns with Tuples

For more advanced control, you can define a custom dash pattern using a tuple. The format is (offset, (on, off, on, off, ...)).

  • offset: The starting point of the dash pattern.
  • The second tuple: A sequence of alternating lengths for dashes (on) and gaps (off).

Example: Custom Dash Patterns

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots(figsize=(10, 6))
# Standard dashed line
ax.plot(x, y, linestyle='--', label='Standard Dashed (5, 5)')
# Custom dash pattern: 10 units on, 5 off, 3 on, 5 off
ax.plot(x, y + 1, linestyle=(0, (10, 5, 3, 5)), label='Custom (10, 5, 3, 5)')
# Custom dash pattern: 20 units on, 10 off
ax.plot(x, y + 2, linestyle=(0, (20, 10)), label='Long Dashes (20, 10)')
# Custom dash pattern: 2 units on, 2 off
ax.plot(x, y + 3, linestyle=(0, (2, 2)), label='Dots (2, 2)')
ax.set_title("Custom Dash Patterns")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.legend()
ax.grid(True)
ax.set_ylim(-2, 5) # Adjust y-axis to see all lines
plt.show()

Output:


Linestyles in Seaborn

Seaborn is built on top of Matplotlib, so it uses the same underlying system for linestyles. You can pass the linestyle parameter directly to Seaborn plotting functions.

Example: Seaborn Line Plot

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Create a sample DataFrame
x = np.linspace(0, 10, 100)
data = pd.DataFrame({
    'Time': x,
    'Signal A': np.sin(x),
    'Signal B': np.cos(x),
    'Signal C': np.sin(x) * 0.8
})
# Use seaborn.lineplot with the 'style' parameter
# 'style' maps a column in the DataFrame to different visual properties
plt.figure(figsize=(10, 6))
sns.lineplot(
    data=data,
    x='Time',
    y='value',
    hue='variable', # Color by variable
    style='variable', # Use different linestyles for each variable
    dashes=True # Seaborn will automatically assign dash patterns
)
# You can also set linestyles manually by passing a dictionary to 'dashes'
# sns.lineplot(..., dashes={'Signal A': '', 'Signal B': '--', 'Signal C': (0, (3, 3))})
"Seaborn Line Plot with Different Linestyles")
plt.xlabel("Time")
plt.ylabel("Amplitude")
plt.grid(True)
plt.show()

Output:

In Seaborn, using style='your_column_name' is a powerful way to automatically apply different linestyles (and markers) to different lines in your plot.


Summary Table

String Code Full Name Description
'solid' Solid line (default)
'dashed' Dashed line
'dotted' Dotted line
'dashdot' Dash-dot line
(None) 'none' No line
(offset, on_off_seq) Custom A tuple to define a custom dash pattern.

Key Takeaways

  1. Use linestyle or ls: This is the main parameter for controlling line patterns in Matplotlib and Seaborn.
  2. Combine with Color: Always pair linestyle with color and linewidth for maximum clarity.
  3. String Codes are Simple: For common styles (, , ), string codes are the easiest.
  4. Tuples are Powerful: For unique or publication-quality dash patterns, use the (offset, (on, off, ...)) tuple format.
  5. Seaborn Leverages Matplotlib: When using Seaborn, you can still use all of Matplotlib's styling capabilities by passing the linestyle parameter directly.
分享:
扫描分享到社交APP
上一篇
下一篇