matplotlib没有画多列柱状图的代码,也没有人写函数,于是自己写了一个 使用时,将x_labels替换为横坐标的刻度,y为嵌套多个小列表的大列表,y中每个列表代表一个系列柱状图 其中gap必须为整数 其余参数含义可见代码函数注释
import matplotlib.pyplot as plt
def ParallelBar(x_labels, y, labels=None, colors=None, width = 0.35, gap=2):
'''
绘制并排柱状图
:param x_labels: list 横坐标刻度标识
:param y: list 列表里每个小列表是一个系列的柱状图
:param labels: list 每个柱状图的标签
:param colors: list 每个柱状图颜色
:param width: float 每条柱子的宽度
:param gap: int 柱子与柱子间的宽度
'''
if labels is not None:
if len(labels) < len(y): raise ValueError('labels的数目不足')
if colors is not None:
if len(colors) < len(y): raise ValueError('颜色colors的数目不足')
if not isinstance(gap, int): raise ValueError('输入的gap必须为整数')
x = [t for t in range(0, len(x_labels)*gap, gap)]
fig, ax = plt.subplots()
for i in range(len(y)):
if labels is not None: l = labels[i]
else: l = None
if colors is not None: color = colors[i]
else: color = None
if len(x) != len(y[i]): raise ValueError('所给数据数目与横坐标刻度数目不符')
plt.bar(x, y[i], label=l, width=width, color=color)
x = [t+width for t in x]
x = [t + (len(y)-1)*width/2 for t in range(0, len(x_labels) * gap, gap)]
ax.set_xticks(x)
ax.set_xticklabels(x_labels)
x_labels = ['a', 'b', 'c', 'd', 'e']
y = [[1,2,3,4,5],[5,4,3,2,1],[1,2,3,2,1]]
labels = ['A', 'B', 'C','D']
c = ['r', 'g', 'b']
ParallelBar(x_labels, y, labels=labels, colors=c, width=0.35, gap=2)
plt.legend()
plt.show()
实现效果:
|