Pandas DataFrame Horizontal Bar Plot
Table Of Contents:
- Syntax ‘plot.barh( )’ Method In Pandas.
- Examples ‘plot.barh( )’ Method.
(1) Syntax:
DataFrame.plot.barh(x=None, y=None, **kwargs)
Description:
Make a horizontal bar plot.
A horizontal bar plot is a plot that presents quantitative data with rectangular bars with lengths proportional to the values that they represent.
A bar plot shows comparisons among discrete categories. One axis of the plot shows the specific categories being compared, and the other axis represents a measured value.
Parameters:
- x: label or position, optional – Allows plotting of one column versus another. If not specified, the index of the DataFrame is used.
- y: label or position, optional – Allows plotting of one column versus another. If not specified, all numerical columns are used.
- color: str, array-like, or dict, optional
The color for each of the DataFrame’s columns. Possible values are:
- A single color string referred to by name, RGB or RGBA code,
for instance ‘red’ or ‘#a98d19’.
- A sequence of color strings referred to by name, RGB or RGBA
code, which will be used for each column recursively. For instance [‘green’,’yellow’] each column’s bar will be filled in green or yellow, alternatively. If there is only a single column to be plotted, then only the first color from the color list will be used.
- A dict of the form {column namecolor}, so that each column will becolored accordingly. For example, if your columns are called a and b, then passing {‘a’: ‘green’, ‘b’: ‘red’} will color bars for column a in green and bars for column b in red.
- **kwargs – Additional keyword arguments are documented in
DataFrame.plot()
.
Returns:
- matplotlib.axes.Axes or np.ndarray of them – An ndarray is returned with one
matplotlib.axes.Axes
per column whensubplots=True
.
(2) Examples Of plot.barh() Method:
Example-1:
df = pd.DataFrame({'lab': ['A', 'B', 'C'], 'val': [10, 30, 20]})
df
Output:
# Basic Plot
ax = df.plot.barh(x='lab', y='val')
Output:
# Plot a whole DataFrame to a horizontal bar plot
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)
df
Output:
ax = df.plot.barh()
Output:
# Plot stacked barh charts for the DataFrame
ax = df.plot.barh(stacked=True)
Output:
# We can specify colors for each column
ax = df.plot.barh(color={"speed": "red", "lifespan": "green"})
Output:
# Plot a column of the DataFrame to a horizontal bar plot
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)
df
ax = df.plot.barh(y='speed')
Output:
ax = df.plot.barh(x='lifespan')