202140420
###################################
20210713 以这个为主
import matplotlib.pyplot as plt
# matplotlib.axes.Axes.hist() 方法的接口
n, bins, patches = plt.hist(x=d, bins='auto', color='#0504aa',
alpha=0.7, rwidth=0.85)
plt.grid(axis='y', alpha=0.75)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('My Very Own Histogram')
plt.text(23, 45, r'$\mu=15, b=3$')
maxfreq = n.max()
# 设置y轴的上限
plt.ylim(ymax=np.ceil(maxfreq / 10) * 10 if maxfreq % 10 else maxfreq + 10)
条形图与直方图的区别:
首先,条形图是用条形的长度表示各类别频数的多少,其宽度(表示类别)则是固定的;
直方图是用面积表示各组频数的多少,矩形的高度表示每一组的频数或频率,宽度则表示各组的组距,因此其高度与宽度均有意义。
其次,由于分组数据具有连续性,直方图的各矩形通常是连续排列,而条形图则是分开排列。
最后,条形图主要用于展示分类数据,而直方图则主要用于展示数据型数据
首先来看一个条形图的例子:
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"C:\Windows\Fonts\simhei.ttf", size=14)
plt.bar([1, 3, 5, 7, 9], [5, 4, 8, 12, 7], label='graph 1')
plt.bar([2, 4, 6, 8, 10], [4, 6, 8, 13, 15], label='graph 2')
# params
# x: 条形图x轴
# y:条形图的高度
# width:条形图的宽度 默认是0.8
# bottom:条形底部的y坐标值 默认是0
# align:center / edge 条形图是否以x轴坐标为中心点或者是以x轴坐标为边缘
plt.legend()
plt.xlabel('number')
plt.ylabel('value')
plt.title(u'测试例子——条形图', FontProperties=font)
plt.show()
【注】如果我们没有明确选择一种颜色,虽然我们做了多个图,但是所有的图都会看起来一样,即颜色是一样。
下面我们看一个直方图的例子:
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"C:\Windows\Fonts\simhei.ttf", size=14)
salary = [2500, 3300, 2700, 5600, 6700, 5400, 3100, 3500, 7600, 7800,
8700, 9800, 10400]
group = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 11000]
plt.hist(salary, group, histtype='bar', rwidth=0.8)
plt.legend()
plt.xlabel('salary-group')
plt.ylabel('salary')
plt.title(u'测试例子——直方图', FontProperties=font)
plt.show()
这是一个简单的工资分布情况图,可以很直观的得到例如在2000-3000水平的人数有2人。