matplotlib multiple bar plot
from matplotlib import pyplot as plt


def bar_plot(ax, data, colors=None, total_width=0.8, single_width=1, legend=True):
    """Draws a bar plot with multiple bars per data point.

    Parameters
    ----------
    ax : matplotlib.pyplot.axis
        The axis we want to draw our plot on.

    data: dictionary
        A dictionary containing the data we want to plot. Keys are the names of the
        data, the items is a list of the values.

        Example:
        data = {
            "x":[1,2,3],
            "y":[1,2,3],
            "z":[1,2,3],
        }

    colors : array-like, optional
        A list of colors which are used for the bars. If None, the colors
        will be the standard matplotlib color cyle. (default: None)

    total_width : float, optional, default: 0.8
        The width of a bar group. 0.8 means that 80% of the x-axis is covered
        by bars and 20% will be spaces between the bars.

    single_width: float, optional, default: 1
        The relative width of a single bar within a group. 1 means the bars
        will touch eachother within a group, values less than 1 will make
        these bars thinner.

    legend: bool, optional, default: True
        If this is set to true, a legend will be added to the axis.
    """

    # Check if colors where provided, otherwhise use the default color cycle
    if colors is None:
        colors = plt.rcParams['axes.prop_cycle'].by_key()['color']

    # Number of bars per group
    n_bars = len(data)

    # The width of a single bar
    bar_width = total_width / n_bars

    # List containing handles for the drawn bars, used for the legend
    bars = []

    # Iterate over all data
    for i, (name, values) in enumerate(data.items()):
        # The offset in x direction of that bar
        x_offset = (i - n_bars / 2) * bar_width + bar_width / 2

        # Draw a bar for every value of that type
        for x, y in enumerate(values):
            bar = ax.bar(x + x_offset, y, width=bar_width * single_width, color=colors[i % len(colors)])

        # Add a handle to the last drawn bar, which we'll need for the legend
        bars.append(bar[0])

    # Draw legend if we need
    if legend:
        ax.legend(bars, data.keys())


if __name__ == "__main__":
    # Usage example:
    data = {
        "a": [1, 2, 3, 2, 1],
        "b": [2, 3, 4, 3, 1],
        "c": [3, 2, 1, 4, 2],
        "d": [5, 9, 2, 1, 8],
        "e": [1, 3, 2, 2, 3],
        "f": [4, 3, 1, 1, 4],
    }

    fig, ax = plt.subplots()
    bar_plot(ax, data, total_width=.8, single_width=.9)
    plt.show()
Python matplotlib multiple bars
fig, ax = plt.subplots()
data = {"Foo": [1, 2, 3, 4], "Zap": [0.1, 0.2], "Quack": [6], "Bar": [1.1, 2.2, 3.3, 4.4, 5.5]}
bar_plot(ax, data, group_stretch=0.8, bar_stretch=0.95, legend=True,
         labels=True, label_fontsize=8, barlabel_offset=0.05,
         bar_labeler=lambda k, i, s: str(round(s, 3)))
fig.show()
Python matplotlib multiple bars
ax = plt.subplot(111)
w = 0.3
ax.bar(x-w, y, width=w, color='b', align='center')
ax.bar(x, z, width=w, color='g', align='center')
ax.bar(x+w, k, width=w, color='r', align='center')
ax.xaxis_date()
ax.autoscale(tight=True)

plt.show()

Python相关代码片段

Conversion of temperature

pandas filter where not empty string

same method with different parameters python

tox ModuleNotFoundError: No module named 'src'

python pdf to png

python env and jupyter kernel

how to remove nested list python

draw.textsize

sec_api python

how to split by multiple things in python

gemini chat bot

pandas max column width

geopandas save as geojson

signals in dajngo

Algorithm Steps for Python Recursion

open file form gui python

ask number gui python

simple windows form python

color selector python

combobox widget in python

Failed to initialize Python.Runtime.dll

loop counter flask

python heartbeat

discord.py remove slash command

Get remainder after division

Sort a list in-place

Remove all elements from a list

os.path.join() function

Arborescence Django

python django projects with source code

check for file python

NameError: name 'scipy' is not defined

django model to dict

add attribute to elementtree

Lambda function to add two numbers

Check if one set is a superset of another

fractions.Fraction class in Python

Invoke a function with its name as a string

Check if a class is a subclass of another class

How to use partial functions

os.path.splitext() function.

Use globals() function to modify a global variable

AttributeError exception

Create a set from a list

Select a random item from a list

program to add two numbers in Python.

get the absolute value of a number in Python

itertools.islice() function in python

Capitalize all words in Python string

max() function in Python

vars() function in Python

setattr() function in Python

get a random integer in a given range in Python

using random.random() function in python

Choose a random item from a list

random.shuffle() function in python

random.choices() function in Python

random.sample() in Python

math.isclose() function in Python

math.comb() in Python

time.localtime() in Python

math.log() in Python

sort array python

get class string py

Binary to Decimal Converter

logging.py

vscode change python version

flask datetime

dbscan clustering implementation python

serving media files in development django

discord bot and flask

histogram of an image in python

numpy get along axis

content delivery network

invalid escape sequence regex python

gnome desktop python

build android app in kivy

python oserror: [errno 24] too many open files

length of array in python

dict.update() with key-value pairs