stacked_barplot: 在 matplotlib 中绘制堆叠柱状图
一个方便使用 pandas DataFrame
在 matplotlib 中绘制堆叠柱状图的函数。
from mlxtend.plotting import stacked_barplot
概述
一个 matplotlib 便利函数,用于从 DataFrame 创建柱状图,其中每个样本与多个类别关联。
参考
- -
示例 1 - 使用 Pandas DataFrame 绘制堆叠柱状图
import pandas as pd
s1 = [1.0, 2.0, 3.0, 4.0]
s2 = [1.4, 2.1, 2.9, 5.1]
s3 = [1.9, 2.2, 3.5, 4.1]
s4 = [1.4, 2.5, 3.5, 4.2]
data = [s1, s2, s3, s4]
df = pd.DataFrame(data, columns=['X1', 'X2', 'X3', 'X4'])
df.columns = ['X1', 'X2', 'X3', 'X4']
df.index = ['Sample1', 'Sample2', 'Sample3', 'Sample4']
df
X1 | X2 | X3 | X4 | |
---|---|---|---|---|
Sample1 | 1.0 | 2.0 | 3.0 | 4.0 |
Sample2 | 1.4 | 2.1 | 2.9 | 5.1 |
Sample3 | 1.9 | 2.2 | 3.5 | 4.1 |
Sample4 | 1.4 | 2.5 | 3.5 | 4.2 |
默认情况下,DataFrame
的索引用作列标签,DataFrame
的列用于绘图图例。
import matplotlib.pyplot as plt
from mlxtend.plotting import stacked_barplot
fig = stacked_barplot(df, rotation=45, legend_loc='best')
API
stacked_barplot(df, bar_width='auto', colors='bgrcky', labels='index', rotation=90, legend_loc='best')
绘制堆叠柱状图的函数
参数
-
df
: pandas.DataFrame一个 pandas DataFrame,其中索引表示 x 轴标签,列包含每行的不同测量值。 bar_width: 'auto' 或 float (默认值: 'auto') 设置柱状图宽度的参数。如果设置为 'auto',宽度将根据数据集中的列数自动确定。 colors: str (默认值: 'bgrcky') 柱状图的颜色。 labels: 'index' 或 iterable (默认值: 'index') 如果设置为 'index',DataFrame 索引将用作 x 轴刻度标签。 rotation: int (默认值: 90) 旋转 x 轴标签的参数。
-
legend_loc
: str (默认值: 'best')绘图图例的位置 {best, upper left, upper right, lower left, lower right} 如果 legend_loc=False 则无图例
返回值
fig
: matplotlib.pyplot figure 对象
示例
有关用法示例,请参见 https://mlxtend.cn/mlxtend/user_guide/plotting/stacked_barplot/