杰瑞科技汇

python plot title

Of course! Creating a title for a plot in Python is a fundamental step for making your data visualizations clear and understandable. The most common library for plotting is Matplotlib, and I'll focus on that first, then cover other popular libraries like Seaborn and Plotly.

python plot title-图1
(图片来源网络,侵删)

Matplotlib: The Standard Library

Matplotlib is the foundation for most plotting in Python. You can set a title using the .title() method.

Basic Title

This is the simplest way to add a title to your plot.

import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create the plot
plt.plot(x, y)
# Add a title"Sine Wave")
# Show the plot
plt.show()

Modifying Title Appearance (Font Size, Weight, etc.)

You can customize the title's appearance using the fontdict parameter or individual keyword arguments.

  • fontsize: Sets the size of the font.
  • fontweight: Sets the weight (e.g., 'bold', 'normal').
  • fontname (or fontfamily): Sets the font family.
  • loc: Sets the alignment ('center', 'left', 'right').
  • pad: Adds padding between the title and the plot.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
# Customize the title with multiple parameters
    "My Custom Sine Wave Plot",
    fontsize=16,
    fontweight='bold',
    fontfamily='serif',
    loc='left',
    pad=20  # Adds space between title and plot
)
plt.xlabel("X-axis (radians)")
plt.ylabel("Y-axis (amplitude)")
plt.show()

Adding Subtitles

For more complex plots, you might want a main title and a subtitle. Matplotlib doesn't have a built-in subtitle function, but you can simulate it by adding a second, smaller title.

python plot title-图2
(图片来源网络,侵删)
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
# Main Title"Sine Wave Analysis", fontsize=18, pad=20)
(using a smaller, lighter font)"A demonstration of trigonometric functions", fontsize=12, style='italic', pad=5)
plt.xlabel("X-axis (radians)")
plt.ylabel("Y-axis (amplitude)")
plt.show()

Note: The second .title() call will technically overwrite the first. The trick is to use the pad parameter to position them correctly. The first title is padded more from the plot, and the second is padded less, creating the illusion of a subtitle.


Seaborn: Statistical Plotting Built on Matplotlib

Seaborn provides a high-level interface for drawing attractive statistical graphics. It uses Matplotlib in the background, so you can use Matplotlib's functions to set the title.

Setting the Title for a Single Plot

Use Matplotlib's plt.title() after creating the Seaborn plot.

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# Load a sample dataset
tips = sns.load_dataset("tips")
# Create a plot
sns.scatterplot(data=tips, x="total_bill", y="tip", hue="day")
# Set the title using Matplotlib"Restaurant Tips vs. Total Bill")
plt.show()

Setting Titles for Facet Grids (Multi-Plot Grids)

This is where Seaborn's own functions become very useful. When you create a grid of plots (e.g., FacetGrid), you can set titles for individual subplots and a main title for the entire figure.

  • .set_titles(): Sets the titles for each subplot.
  • .suptitle(): Sets a main title for the entire figure (a Matplotlib function).
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
# Create a FacetGrid
g = sns.FacetGrid(tips, col="day", row="time", height=4, aspect=1)
# Map a plot to the grid
g.map(sns.scatterplot, "total_bill", "tip")
# Set titles for each subplot (e.g., "Lunch", "Dinner", etc.)
g.set_titles("{row_name} | {col_name}")
# Set a main title for the entire figure
plt.suptitle("Tips by Day and Meal Time", y=1.03) # y=1.03 adjusts the title position
plt.show()

Plotly: Interactive Plotting

Plotly is famous for creating interactive, publication-quality graphs. The syntax is slightly different as it's an object-oriented library.

Basic Title

When you create a figure with go.Figure(), you pass a layout argument that controls all aspects of the figure's appearance, including the title.

import plotly.graph_objects as go
import numpy as np
# Sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create the figure and define the layout in one step
fig = go.Figure(
    data=go.Scatter(x=x, y=y, name="Sine Wave"),
    layout=go.Layout(
        title="Interactive Sine Wave", # Main title
        xaxis_title="X-axis (radians)", # X-axis label
        yaxis_title="Y-axis (amplitude)"  # Y-axis label
    )
)
fig.show()

Modifying Title Appearance

You customize the title by creating a dict for the title key in the layout.

import plotly.graph_objects as go
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
fig = go.Figure(
    data=go.Scatter(x=x, y=y),
    layout=go.Layout(
        title=dict(
            text="My Custom Plotly Title",
            x=0.5, # Position from 0 (left) to 1 (right)
            y=0.9, # Position from 0 (bottom) to 1 (top)
            xanchor='center', # Anchors the title's x position
            yanchor='top',    # Anchors the title's y position
            font=dict(
                family="Arial",
                size=24,
                color="crimson"
            )
        )
    )
)
fig.show()

Summary and Best Practices

Library Function/Method Key Parameters
Matplotlib plt.title() fontsize, fontweight, fontfamily, loc, pad
Seaborn plt.title() (for single plots)
g.set_titles() (for subplots)
plt.suptitle() (for figure title)
Same as Matplotlib, plus Seaborn's template strings like {col_name}.
Plotly layout=go.Layout(title=...) A dict containing text, x, y, font, etc.

Best Practices:

  1. Be Descriptive: A good title should answer the question "What is this plot showing?" without needing to read the axis labels or caption.
  2. Be Concise: Avoid overly long titles. If you need more context, use a caption below the plot.
  3. Use Consistent Styling: If you're creating multiple plots for a report or dashboard, use the same font size, weight, and color for all titles to maintain a professional look.
  4. Consider Your Audience: A title for a scientific paper will be more formal and technical than one for a business dashboard.
分享:
扫描分享到社交APP
上一篇
下一篇