首页 > 解决方案 > 未引用“轴”时设置绘图背景颜色

问题描述

我有一个函数来创建堆积条形图来处理df类似于这个示例的 s:

import pandas as pd
import numpy as np

numrows = 5
index = ['A', 'B', 'C', 'D', 'E', 'F']
test = pd.DataFrame({
    'Yes': (0.4083, 0.4617, 0.284, 0.607, 0.3634, 0.4075),
    'No':  (0.5875, 0.5383, 0.716, 0.393, 0.635, 0.5925),
    'Other': (0.00417, 0, 0, 0, 0.0016668,0)},
    index = index)

臀部功能看起来像这样

def bar_plot(df):
    N = len(df) # number of rows
    ind = np.arange(N)
    width = 0.35
    num_y_cats = len(df.columns)

    p_s = []
    p_s.append(plt.bar(ind, df.iloc[:, 0], width, color='#000000'))
    for i in range(1, len(df.columns)):
        p_s.append(plt.bar(ind, df.iloc[:, i], width, color = ''.join(('#', 6 * str(i))), bottom = np.sum(df.iloc[:,:i], axis=1)))
    plt.ylabel('[%]')
    plt.title('Title')            
    x_ticks_names = tuple([item for item in df.index])
    plt.xticks(ind, x_ticks_names)
    plt.yticks(np.arange(0, 1.1, 0.1))

    plt.legend(p_s, df.columns, bbox_to_anchor = (0.5, -0.35), loc = 'lower center', ncol = 3, borderaxespad = 0)
    plt.show()
    plt.close()

我想更改背景和图例背景的设计-但有关此问题的文档和类似问题都只会导致建议使用axes对象方法的响应-但是,我没有在任何地方明确使用过. 因此,我对修改背景布局的地方感到困惑(例如,将其设置为白色或黄色)。

非常感谢您的任何指示和帮助!

标签: pythonmatplotlibbar-chart

解决方案


您可以使用创建轴实例subplots(),然后使用它来绘制条形图。然后您可以设置轴和图例框的面颜色,如下所示

def bar_plot(df):
    N = len(df) # number of rows
    ind = np.arange(N)
    width = 0.35
    num_y_cats = len(df.columns)
    fig, ax = plt.subplots() # <--- Create an axis instance
    p_s = []
    p_s.append(ax.bar(ind, df.iloc[:, 0], width, color='#000000'))
    for i in range(1, len(df.columns)):
        p_s.append(plt.bar(ind, df.iloc[:, i], width, color = ''.join(('#', 6 * str(i))), bottom = np.sum(df.iloc[:,:i], axis=1)))
    plt.ylabel('[%]')
    plt.title('Title')            
    x_ticks_names = tuple([item for item in df.index])
    plt.xticks(ind, x_ticks_names)
    plt.yticks(np.arange(0, 1.1, 0.1))
    ax.set_facecolor('yellow') # <--- Set the figure background color
    leg = plt.legend(p_s, df.columns, bbox_to_anchor = (0.5, -0.35), loc = 'lower center', ncol = 3, borderaxespad = 0)
    leg_frame = leg.get_frame()
    leg_frame.set_facecolor('lightgreen') # <--- Set the legend background color
    plt.show()
    plt.close()

在此处输入图像描述


推荐阅读