Python matplotlib已隐藏条形图(系列、数据和类别)

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

我将序列、数据和类别输入到一个函数中,以便使用matplotlib创建一个被回避的条形图。
我已经成功地创建了一个堆叠图,但我想创建一个回避条形图。
这是我已经设法创建(堆叠酒吧):

这是我想要创建的(躲避条):

#
# File: bar_dodged.py
# Version 1
# License: https://opensource.org/licenses/GPL-3.0 GNU Public License
#

import matplotlib.pyplot as plt
import numpy as np

def bar_dodged(series_labels: list = ['Minor', 'Low'],
        data: list = [
                [1, 2, 3, 4],
                [5, 6, 7, 8]
            ],
        category_labels: list = ['01/2023', '02/2023', '03/2023', '04/2023'],
        bar_background_colors: list = ['tab:orange', 'tab:green'],
        bar_text_colors: list = ['white', 'grey'],
        direction: str = "vertical",
        x_labels_rotation: int = 0,
        y_label: str = "Quantity (units)",
        figsize: tuple = (18, 5),
        reverse: bool = False,
        file_path: str = ".",
        file_name: str = "bar_dodged.png"):
    """

    :param series_labels:
    :param data:
    :param category_labels:
    :param bar_background_colors:
    :param bar_text_colors:
    :param direction:
    :param x_labels_rotation:
    :param y_label:
    :param figsize:
    :param reverse:
    :param file_path:
    :param file_name:
    :return:
    """
    # Debugging
    print(f"\n")
    print(f"bar_dodged() :: series_labels={series_labels}")
    print(f"bar_dodged() :: data={data}")
    print(f"bar_dodged() :: category_labels={category_labels}")
    print(f"bar_dodged() :: bar_background_colors={bar_background_colors}")

    # Set size
    plt.figure(figsize=figsize)

    # Plot!
    show_values = True
    value_format = "{:.0f}"
    grid = False
    ny = len(data[0])
    ind = list(range(ny))

    axes = []
    cum_size = np.zeros(ny)

    data = np.array(data)

    if reverse:
        data = np.flip(data, axis=1)
        category_labels = reversed(category_labels)

    for i, row_data in enumerate(data):
        color = bar_background_colors[i] if bar_background_colors is not None else None
        axes.append(plt.bar(ind, row_data, bottom=cum_size,
                            label=series_labels[i], color=color))
        cum_size += row_data

    if category_labels:
        plt.xticks(ind, category_labels)

    if y_label:
        plt.ylabel(y_label)

    plt.legend()

    if grid:
        plt.grid()

    if show_values:
        for axis in axes:
            for bar in axis:
                w, h = bar.get_width(), bar.get_height()
                plt.text(bar.get_x() + w/2, bar.get_y() + h/2,
                         value_format.format(h), ha="center",
                         va="center")

    # Rotate
    plt.xticks(rotation=x_labels_rotation)

    # Two  lines to make our compiler able to draw:
    plt.savefig(f"{file_path}/{file_name}", bbox_inches='tight', dpi=200)

if __name__ == '__main__':
    # Usage example:

    series_labels = ['Globally', 'Customer']
    data = [[9, 6, 5, 4, 8], [8, 5, 4, 3, 7]]
    category_labels = ['Feb/2023', 'Dec/2022', 'Nov/2022', 'Oct/2022', 'Sep/2022']
    bar_background_colors = ['#800080', '#ffa503']

    bar_dodged(series_labels=series_labels, data=data, category_labels=category_labels,
               bar_background_colors=bar_background_colors)

我必须在代码中更改什么才能使图表被隐藏?

zd287kbt

zd287kbt1#

要做到这一点,你只需要在for循环中修改一行,在那里你正在绘制条形图,把axes.append()修改为below ...

axes.append(plt.bar([element + 0.2*i for element in ind], 
                    row_data, width = 0.2, #bottom=cum_size,
                    label=series_labels[i], color=color))

这将基本上改变条的x位置为0,1,2 ..(对于第一次运行,当1 = 0时),并在第二次运行时添加0.2。我使用width = 0.2将条形宽度保持为0.2。如果您想要更厚的条形,您可以更改它。此外,我删除了bottom,这意味着,每个条形/矩形将从0开始。希望这是你正在寻找的...

    • 情节**

相关问题