Matplotlib库基础-条形图

以长方形的长度为变量的统计图,多用来比较多个分类项目的数据大小,通常用于较小的数据集分析。

#条形图 x = [1,2,3,4,5]

y = [10,30,50,20,40]

plt.bar(x,y)

plt.xticks(x,['A','B','C','D','E'])#重命名分类轴

plt.show()

输出

分组条形图

labels = ['G1', 'G2', 'G3', 'G4', 'G5']

men_means = [20, 34, 30, 35, 27]

women_means = [25, 32, 34, 20, 25]

x = np.arange(len(labels))  # 先使用数字作为横轴,可以将数字均分成两份用来画两个条形图

width = 0.35  # 条形图的宽度

rects1 = plt.bar(x - width/2, men_means, width, label='Men')

rects2 = plt.bar(x + width/2, women_means, width, label='Women')

# 添加标签等.

plt.ylabel('成绩')

plt.title('成绩按性别分组')

plt.xticks(x)

plt.xticks(x,labels)

plt.legend()

#给条形图添加显示Y轴的数字

def autolabel(rects):

    """Attach a text label above each bar in *rects*, displaying its height."""

    for rect in rects:

        height = rect.get_height()

        plt.annotate('{}'.format(height),

                    xy=(rect.get_x() + rect.get_width() / 2, height),

                    xytext=(0, 3),  # 3 points vertical offset

                    textcoords="offset points",

                    ha='center', va='bottom')

autolabel(rects1)

autolabel(rects2)

plt.show()

输出

条形图没有形式Y轴数量的属性,需要自己写函数去使用annotate()函数调整显示的Y轴数量。

参数error_kw={'ecolor':'0.1', # 指定误差线的颜色 'capsize':6 # 指定误差线两头横线的宽度 }

水平条状图

相关函数barh(),其显示的条形图与上例中的位置刚好相反,不过参数的使用一致。另外,方差使用xerr,而不是yerr.

index = np.arange(5)

values = [5,6,7,8,9]

std = [0.8,1,0.4,0.9,1.3]

plt.title('水平条状图')

plt.barh(index, values, xerr=std,  error_kw={'ecolor':'0.1',  'capsize':6 }, alpha=0.7,  label='例一')

plt.yticks(index, ['A','B','C','D','E'])

plt.legend(loc=5)

plt.show()

输出:

为pandas DataFrame 生成多序列条状图

import pandas as pd 
data = {'one':[1,3,4,5,5], 'two':[2,4,5,2,7], 'three':[3,2,4,8,9]}
df = pd.DataFrame(data) 
df.plot(kind='bar') # 通过df调用plot(),指定输出类型即可 
plt.show()

data = {'one':[1,3,4,5,5], 'two':[2,4,5,2,7], 'three':[3,2,4,8,9]} 
df = pd.DataFrame(data) 
df.plot(kind='barh') # 通过df调用plot(),指定输出类型即可 
plt.show()

多序列堆积条状图

要把简单的多序列条状图转换为堆积图,需要在每个bar()函数中添加bottom关键字参数,把每个序列赋给相应的bottom关键字参数

series1 = np.array([3,4,5,3])

series2 = np.array([1,2,2,5])

series3 = np.array([2,3,3,4])

index = np.arange(4)

plt.bar(index,series1,color='r')

plt.bar(index,series2,color='b', bottom=series1)

plt.bar(index,series3,color='g', bottom=(series2+series1))

plt.xticks(index+0.4, ['Jan15','Feb15','Mar15','Apr15'])

plt.show()

series1 = np.array([3,4,5,3])

series2 = np.array([1,2,2,5])

series3 = np.array([2,3,3,4])

index = np.arange(4)

plt.barh(index,series1,color='r')

plt.barh(index,series2,color='b', left=series1)  # 注意,这里使用left而不是bottom

plt.barh(index,series3,color='g', left=(series2+series1))

plt.yticks(index+0.4, ['Jan15','Feb15','Mar15','Apr15'])

plt.show()

为pandas DataFrame 绘制堆积条状图

import pandas as pd

data = {'one':[1,3,4,5,5],

        'two':[2,4,5,2,7],

        'three':[3,2,4,8,9]}

df = pd.DataFrame(data)

df.plot(kind='bar',stacked=True)  # stacked属性指定是否为堆积图类型

plt.show()

官网上有较多的例子可以参考:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.bar.html?highlight=bar#matplotlib.pyplot.bar

你可能感兴趣的:(Matplotlib库基础-条形图)