Add parameters to title when drawing graphics in plt

If you want to embed the passed parameters in the title, you can use string formatting methods, such as Python's format() method or f-string (Python 3.6+). This dynamically inserts the parameter's value into the title string.

Here are two examples:

Use the format() method:

import matplotlib.pyplot as plt

def plot_with_parameter(title_param):
    x = [1, 2, 3, 4, 5]
    y = [10, 20, 15, 30, 25]
    
    plt.plot(x, y)
    plt.title("示例折线图 - {}".format(title_param))
    plt.xlabel("X轴")
    plt.ylabel("Y轴")
    plt.show()

# 调用函数,并传递参数作为标题的一部分
parameter = "参数值"
plot_with_parameter(parameter)
使用 f-string(Python 3.6+):
import matplotlib.pyplot as plt

def plot_with_parameter(title_param):
    x = [1, 2, 3, 4, 5]
    y = [10, 20, 15, 30, 25]
    
    plt.plot(x, y)
    plt.title(f"示例折线图 - {title_param}")
    plt.xlabel("X轴")
    plt.ylabel("Y轴")
    plt.show()

Call the function, passing the parameters as part of the header

parameter = "parameter value"
plot_with_parameter(parameter)
In the above example, a function named plot_with_parameter() is defined, where title_param is a parameter that will be used as part of the title. Curly braces {} are used in the title to place space, and the actual parameter values ​​are passed in the format() method or f-string. When the function is called, arguments are passed to the plot_with_parameter() function, which inserts the parameter values ​​into the title, thus dynamically generating the title with the parameters.

Guess you like

Origin blog.csdn.net/qq_45410037/article/details/131900052