Pandas Series: plot.barh() function
Series-plot.barh() function
The plot.barh() function is used to create 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.
Syntax:
Series.plot.barh(self, x=None, y=None, **kwargs)
Parameters:
Name | Description | Type/Default Value | Required / Optional |
---|---|---|---|
x | Column to be used for categories. | label or position, default DataFrame.index | Required |
y | Columns to be plotted from the DataFrame. | label or position, default All numeric columns in dataframe | Required |
**kwds | Keyword arguments to pass on to DataFrame.plot(). |
Returns: matplotlib.axes.Axes or numpy.ndarray of them.
Example - Basic example:
Python-Pandas Code:
import numpy as np
import pandas as pd
df = pd.DataFrame({'lab':['P', 'Q', 'R'], 'val':[6, 26, 16]})
ax = df.plot.barh(x='lab', y='val')
Output:
Example - Plot a whole DataFrame to a horizontal bar plot:
Python-Pandas Code:
import numpy as np
import pandas as pd
speed = [0.1, 17.5, 30, 38, 42, 59, 77]
lifespan = [2, 6, 60, 1.5, 21, 10, 24]
index = ['elephant', 'pig', 'deer',
'goat', 'cat', 'fox', 'horse']
df = pd.DataFrame({'speed': speed,
'lifespan': lifespan}, index=index)
ax = df.plot.barh()
Output:
Example - Plot a column of the DataFrame to a horizontal bar plot:
Python-Pandas Code:
import numpy as np
import pandas as pd
speed = [0.1, 17.5, 30, 38, 42, 59, 77]
lifespan = [2, 6, 60, 1.5, 21, 10, 24]
index = ['elephant', 'pig', 'deer',
'goat', 'cat', 'fox', 'horse']
df = pd.DataFrame({'speed': speed,
'lifespan': lifespan}, index=index)
ax = df.plot.barh(y='speed')
Output:
Example - Plot DataFrame versus the desired column:
Python-Pandas Code:
import numpy as np
import pandas as pd
speed = [0.1, 17.5, 30, 38, 42, 59, 77]
lifespan = [2, 6, 60, 1.5, 21, 10, 24]
index = ['elephant', 'pig', 'deer',
'goat', 'cat', 'fox', 'horse']
df = pd.DataFrame({'speed': speed,
'lifespan': lifespan}, index=index)
ax = df.plot.barh(x='lifespan')
Output:
Previous: Series-plot.bar() function
Next: Series-plot.box() function
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/pandas/series/series-plot-barh.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics