Python matplotlib :如何组合现有图形

aij0ehis  于 2023-03-03  发布在  Python
关注(0)|答案(1)|浏览(174)

我已经构建了一个函数,并将其应用于不同的部分字符串--所有这些都是有效的(参见下面的步骤)。
应用于部分字符串的函数可以工作,但是会为每个部分字符串创建不同的图形。有没有办法合并所有这些图形?
1.基于部分字符串创建新 Dataframe
1.根据新 Dataframe 中的列定义x和y值
1.训练测试拆分数据以查找最佳度和RMSE(查找10度外的最佳拟合)
1.基于最佳次数创建多项式函数
1.绘制原始数据和适当颜色编码的多项式函数
1.找出特定x值和回归线的交点,并标记它们

# Finding best fit and graphing it
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split

def graph(number):
    # Creating a new dataframe for each type of security
    df = mat[mat['Security'].str.contains(number)]
    df = df.reset_index(drop = True).sort_values('Years')
    
    # Defining x and y values
    x = df['Years']
    y = df['Rate']
    
    # Train Test Split
    rmses = []
    degrees = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    min_rmse, min_deg = 1e10, 0
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2)
    x_train = x_train.values.reshape(-1, 1)
    x_test = x_test.values.reshape(-1, 1)
    # For degrees up to 10
    for deg in degrees:
        poly_features = PolynomialFeatures(degree = deg, include_bias = False)
        x_poly_train = poly_features.fit_transform(x_train)
        
        poly_reg = LinearRegression()
        poly_reg.fit(x_poly_train, y_train)
        
        x_poly_test = poly_features.fit_transform(x_test)
        poly_predict = poly_reg.predict(x_poly_test)
        poly_mse = mean_squared_error(y_test, poly_predict)
        poly_rmse = np.sqrt(poly_mse)
        rmses.append(poly_rmse)
        
        if min_rmse > poly_rmse:
            min_rmse = poly_rmse
            min_deg = deg
            
    # Creating polynomial functions based on best degree
    z = np.polyfit(x, y, min_deg)
    f = np.poly1d(z)
    
    # Setting colour gradients and colours dependent on bond type
    '''
    When adding a new type, specify a colour gradient following the format below
    Add another elif statement following the same format
    '''
    gradient_blue = get_color_gradient('#003060', '#B9D9EB', len(x))
    gradient_red = get_color_gradient('#750000', '#F5D2D2', len(x))
    gradient_green = get_color_gradient('#1A4314', '#B2D2A4', len(x))
    gradient_purple = get_color_gradient('#4B0082', '#E6E6FA', len(x))
    
    if bondtype == '1':
        gradient = gradient_blue
        line = 'Blue'
        name = 'Ontario'
    elif bondtype == '2':
        gradient = gradient_red
        line = 'Red'
        name = 'CMB'
    elif bondtype == '3':
        gradient = gradient_green
        line = 'Green'
        name = 'BCMFA'
    else:
        gradient = gradient_purple
        line = 'Purple'
        name = 'Other'

    # Plotting the data points and regression
    fig, ax = plt.subplots(figsize = (18, 8))
    ax.scatter(x, y, color = gradient)
    plt.plot(x, f(x), label = name + ' degree ' + str(min_deg), color = line)
    
    # Finding the points where regression intersects with 3-, 4-, and 5-year maturity
    mat_pt = [3, 4, 5]
    mat_345 = np.interp(mat_pt, x, f(x))
    # Graphing the points
    ax.scatter(mat_pt, mat_345, color = line, marker = '*', s = 200, label = name)
    # Labelling the points
    for x, y in zip(mat_pt, mat_345):
        label = '{:.2f}'.format(y)
        plt.annotate(label,
                    (x, y),
                    textcoords = 'offset points',
                    xytext = (15, -5),
                    ha = 'left',
                    color = line)
    
    # Adding vertical lines at years of maturity = 3, 4, 5 and horizontal line at OIS = 0
    plt.axvline(x = 3, color = 'grey', linewidth = 0.5)
    plt.axvline(x = 4, color = 'grey', linewidth = 0.5)
    plt.axvline(x = 5, color = 'grey', linewidth = 0.5)
    plt.axhline(y = 0, color = 'black', linewidth = 0.5, linestyle = 'dashed')
    
    # Formatting the plot
    plt.xlabel('Years', size = 15)
    plt.ylabel('Rate', size = 15)
    plt.title('Rate: ' + today_str, size = 20)
    ax.legend(loc = 'upper left')
    
    return plt

当我将函数应用于每个子字符串时,我得到了多个图形(每个函数一个),但我需要一个所有图都组合在一起的图形

我的输出

ont = graph('ONT')
cmb = graph('CANHOU')
bcmfa = graph('BCMFA')

所需输出

mpbci0fu

mpbci0fu1#

因为您调用graph函数的次数不同,所以会得到三个不同的图:

ont = graph('ONT')
cmb = graph('CANHOU')
bcmfa = graph('BCMFA')

相反,我建议你:
1.修改函数以接受证券列表,这样就可以执行final_plot = graph(['ONT', 'CANHOU', 'BCMFA'])
1.修改函数以接受图形和轴作为输入,并将修改后的版本作为输出输出输出。然后,您可以执行以下操作:

fig, ax = plt.subplots()
_fig, _ax = graph('ONT', fig, ax)
_fig, _ax = graph('CANHOU', _fig, _ax) # I'm just overwriting the old versions of the underscore variables here, instead of making new variables
final_plot, final_ax = graph('BCMFA', _fig, _ax)
final_plot.savefig("blah.jpeg")

相关问题