matplotlib.pyplot.grouped_bar#

matplotlib.pyplot.grouped_bar(heights,*,positions=None,group_spacing=1.5,bar_spacing=0,tick_labels=None,labels=None,orientation='vertical',colors=None,**kwargs)[source]#

Make a grouped bar plot.

Added in version 3.11:The API is still provisional. We may still fine-tune some aspects based onuser-feedback.

Grouped bar charts visualize a collection of categorical datasets. Each valuein a dataset belongs to a distinct category and these categories are the sameacross all datasets. The categories typically have string names, but couldalso be dates or index keys. The values in each dataset are represented by asequence of bars of the same color. The bars of all datasets are groupedtogether by their shared categories. The category names are drawn as the ticklabels for each bar group. Each dataset has a distinct bar color, and canoptionally get a label that is used for the legend.

Example:

grouped_bar([dataset_0,dataset_1,dataset_2],tick_labels=['A','B'],labels=['dataset 0','dataset 1','dataset 2'])

(Sourcecode,2x.png,png)

Parameters:
heightslist of array-like or dict of array-like or 2D array or pandas.DataFrame

The heights for all x and groups. One of:

  • list of array-like: A list of datasets, each dataset must havethe same number of elements.

    #           category_A, category_Bdataset_0 = [value_0_A, value_0_B]dataset_1 = [value_1_A, value_1_B]dataset_2 = [value_2_A, value_2_B]

    Example call:

    grouped_bar([dataset_0,dataset_1,dataset_2])
  • dict of array-like: A mapping from names to datasets. Each dataset(dict value) must have the same number of elements.

    Example call:

    data_dict={'ds0':dataset_0,'ds1':dataset_1,'ds2':dataset_2}grouped_bar(data_dict)

    The names are used aslabels, i.e. this is equivalent to

    grouped_bar(data_dict.values(),labels=data_dict.keys())

    When using a dict input, you must not passlabels explicitly.

  • a 2D array: The rows are the categories, the columns are the differentdatasets.

                dataset_0 dataset_1 dataset_2category_A    ds0_a     ds1_a     ds2_acategory_B    ds0_b     ds1_b     ds2_b

    Example call:

    categories=["A","B"]dataset_labels=["dataset_0","dataset_1","dataset_2"]array=np.random.random((2,3))grouped_bar(array,tick_labels=categories,labels=dataset_labels)
  • apandas.DataFrame.

    The index is used for the categories, the columns are used for thedatasets.

    df=pd.DataFrame(np.random.random((2,3)),index=["A","B"],columns=["dataset_0","dataset_1","dataset_2"])grouped_bar(df)

    i.e. this is equivalent to

    grouped_bar(df.to_numpy(),tick_labels=df.index,labels=df.columns)

    Note thatgrouped_bar(df) produces a structurally equivalent plot likedf.plot.bar().

positionsarray-like, optional

The center positions of the bar groups. The values have to be equidistant.If not given, a sequence of integer positions 0, 1, 2, ... is used.

tick_labelslist of str, optional

The category labels, which are placed on ticks at the centerpositionsof the bar groups. If not set, the axis ticks (positions and labels) areleft unchanged.

labelslist of str, optional

The labels of the datasets, i.e. the bars within one group.These will show up in the legend.

group_spacingfloat, default: 1.5

The space between two bar groups as a multiple of bar width.

The default value of 1.5 thus means that there's a gap of1.5 bar widths between bar groups.

bar_spacingfloat, default: 0

The space between bars as a multiple of bar width.

orientation{"vertical", "horizontal"}, default: "vertical"

The direction of the bars.

colorslist ofcolor, optional

A sequence of colors to be cycled through and used to color barsof the different datasets. The sequence need not be exactly thesame length as the number of provided y, in which case the colorswill repeat from the beginning.

If not specified, the colors from the Axes property cycle will be used.

**kwargsRectangle properties

Properties applied to all bars. The following properties additionallyaccept a sequence of values corresponding to the datasets inheights:

  • edgecolor

  • facecolor

  • linewidth

  • linestyle

  • hatch

Property

Description

agg_filter

a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image

alpha

float or None

angle

unknown

animated

bool

antialiased oraa

bool or None

bounds

(left, bottom, width, height)

capstyle

CapStyle or {'butt', 'projecting', 'round'}

clip_box

BboxBase or None

clip_on

bool

clip_path

Patch or (Path, Transform) or None

color

color

edgecolor orec

color or None

facecolor orfc

color or None

figure

Figure orSubFigure

fill

bool

gid

str

hatch

{'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}

hatch_linewidth

unknown

hatchcolor

color or 'edge' or None

height

unknown

in_layout

bool

joinstyle

JoinStyle or {'miter', 'round', 'bevel'}

label

object

linestyle orls

{'-', '--', '-.', ':', '', (offset, on-off-seq), ...}

linewidth orlw

float or None

mouseover

bool

path_effects

list ofAbstractPathEffect

picker

None or bool or float or callable

rasterized

bool

sketch_params

(scale: float, length: float, randomness: float)

snap

bool or None

transform

Transform

url

str

visible

bool

width

unknown

x

unknown

xy

(float, float)

y

unknown

zorder

float

Returns:
_GroupedBarReturn

A provisional result object. This will be refined in the future.For now, the guaranteed API on the returned object is limited to

  • the attributebar_containers, which is a list ofBarContainer, i.e. the results of the individualbarcalls for each dataset.

  • aremove() method, that remove all bars from the Axes.See alsoArtist.remove().

See also

bar

A lower-level API for bar plots, with more degrees of freedom like individual bar sizes and colors.

Notes

For a better understanding, we compare thegrouped_bar API withthose ofbar andboxplot.

Comparison to bar()

grouped_bar intentionally deviates from thebar API in someaspects.bar(x,y) is a lower-level API and places bars with heightyat explicit positionsx. It also allows to specify individual bar widthsand colors. This kind of detailed control and flexibility is difficult tomanage and often not needed when plotting multiple datasets as a grouped barplot. Therefore,grouped_bar focusses on the abstraction of bar plotsas visualization of categorical data.

The following examples may help to transfer frombar togrouped_bar.

Positions are de-emphasized due to categories, and default to integer values.If you have usedrange(N) as positions, you can leave that value out:

bar(range(N),heights)grouped_bar([heights])

If needed, positions can be passed as keyword arguments:

bar(x,heights)grouped_bar([heights],positions=x)

To place category labels inbar you could use the argumenttick_label or use a list of category names asx.grouped_bar expects them in the argumenttick_labels:

bar(range(N),heights,tick_label=["A","B"])bar(["A","B"],heights)grouped_bar([heights],tick_labels=["A","B"])

Dataset labels, which are shown in the legend, are still passed via thelabel parameter:

bar(...,label="dataset")grouped_bar(...,label=["dataset"])

Comparison to boxplot()

Both,grouped_bar andboxplot visualize categorical datafrom multiple datasets. The basic API ontick_labels andpositionsis the same, so that you can easily switch between plotting allindividual values asgrouped_bar or the statistical distributionper category asboxplot:

grouped_bar(values,positions=...,tick_labels=...)boxplot(values,positions=...,tick_labels=...)

Examples usingmatplotlib.pyplot.grouped_bar#

Hat graph

Hat graph