pandas.Series.plot.bar#

Series.plot.bar(x=None, y=None, **kwargs)[源代码]#

垂直条形图。

条形图是一种图形,它以长度与所代表的值成比例的矩形条展示分类数据。条形图显示了离散类别之间的比较。图形的一个轴显示正在比较的特定类别,另一个轴表示测量值。

Parameters:
x标签或位置,可选。

允许将一列绘制到另一列。如果未指定,则使用 DataFrame 的索引。

y标签或位置,可选。

允许将一列绘制到另一列。如果未指定,则使用所有数字列。

colorstr, array-like, or dict, optional

DataFrame 列的颜色。可能的值包括:

  • 按名称、RGB 或 RGBA 代码引用的单个颜色字符串,

    例如 ‘red’ 或 ‘#a98d19’。

  • 按名称、RGB 或 RGBA 引用的颜色字符串序列

    代码,将依次递归用于每列。例如 [‘green’,’yellow’],每列的条形将依次填充为绿色或黄色。如果只有一列要绘制,则只使用颜色列表中的第一种颜色。

  • 形式为 {列名颜色} 的字典,以便每列将

    相应地着色。例如,如果您的列名为 ab,则传递 {‘a’: ‘green’, ‘b’: ‘red’} 将使列 a 的条形着色为绿色,列 b 的条形着色为红色。

**kwargs

附加关键字参数在 DataFrame.plot() 中有详细说明。

Returns:
matplotlib.axes.Axes 或它们的 np.ndarray

subplots=True 时,将返回一个 ndarray,其中每列有一个 matplotlib.axes.Axes

参见

DataFrame.plot.barh

横向条形图。

DataFrame.plot

绘制 DataFrame 的图形。

matplotlib.pyplot.bar

使用 matplotlib 绘制条形图。

Examples

基本图。

>>> df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]})
>>> ax = df.plot.bar(x='lab', y='val', rot=0)
../../_images/pandas-Series-plot-bar-1.png

将整个 DataFrame 绘制为条形图。每列分配有不同的颜色,并且每行嵌套在水平轴上的组中。

>>> speed = [0.1, 17.5, 40, 48, 52, 69, 88]
>>> lifespan = [2, 8, 70, 1.5, 25, 12, 28]
>>> index = ['snail', 'pig', 'elephant',
...          'rabbit', 'giraffe', 'coyote', 'horse']
>>> df = pd.DataFrame({'speed': speed,
...                    'lifespan': lifespan}, index=index)
>>> ax = df.plot.bar(rot=0)
../../_images/pandas-Series-plot-bar-2.png

为 DataFrame 绘制堆叠条形图

>>> ax = df.plot.bar(stacked=True)
../../_images/pandas-Series-plot-bar-3.png

除了嵌套之外,还可以使用 subplots=True 按列拆分图形。在这种情况下,将返回 numpy.ndarraymatplotlib.axes.Axes

>>> axes = df.plot.bar(rot=0, subplots=True)
>>> axes[1].legend(loc=2)  
../../_images/pandas-Series-plot-bar-4.png

如果您不喜欢默认颜色,可以指定每列的颜色。

>>> axes = df.plot.bar(
...     rot=0, subplots=True, color={"speed": "red", "lifespan": "green"}
... )
>>> axes[1].legend(loc=2)  
../../_images/pandas-Series-plot-bar-5.png

绘制单个列。

>>> ax = df.plot.bar(y='speed', rot=0)
../../_images/pandas-Series-plot-bar-6.png

仅绘制 DataFrame 的选定类别。

>>> ax = df.plot.bar(x='lifespan', rot=0)
../../_images/pandas-Series-plot-bar-7.png