# matplotlib 直方图

import matplotlib.pyplot as plt
import numpy as np
X = np.random.randint(0,101,1000)
plt.hist(X,color ="cyan",edgecolor='k')
plt.show()

hist()函数的参数中：

X 是长度为N的数组，表示单组数据；或者是长度为N的数组组成的序列，表示多组数据

color 表示 bar 中心区域的颜色

edgecolor 表示 bar 边缘的颜色

X为序列时，可显示多组数据的分布：

import matplotlib.pyplot as plt
import numpy as np
X1 = np.random.randint(0,101,1000)
X2 = np.random.randint(0,101,1000)
plt.hist([X1,X2],color =["cyan","red"],edgecolor='k',label=["A","B"])
#为了容易区分，color可为与X长度相符的序列
#label是数据分组标签
plt.legend()
plt.show()

plt.hist([X1,X2], stacked=True, color =["cyan","red"],edgecolor='k',label=["A","B"])

plt.hist([X1,X2],histtype='stepfilled',stacked= True, color =["cyan","red"],edgecolor='k',label=["A","B"]

import matplotlib.pyplot as plt
import numpy as np
X1 = np.random.randint(0,101,1000)
bins = [0,25,60,85,100]
plt.hist(X1,bins =bins, color ="b",edgecolor='k')
plt.xticks(bins)#设置x轴刻度和bins一致
plt.title("Histogram",fontsize=18,color="red")
plt.xlabel("x label...")
plt.ylabel("Qty.")
plt.show()

import matplotlib
from  matplotlib import ticker
import matplotlib.pyplot as plt
import numpy as np

matplotlib.rcParams["font.sans-serif"] = ["SimHei"]#设置全局字体
X1 = np.random.randint(0,101,1000)
w =np.ones_like(X1)#都为1
bins = [0,25,60,85,100]

#设置Y轴数据以百分比显示:
yticks = ticker.PercentFormatter(xmax=1, symbol='%', is_latex=True)
plt.gca().yaxis.set_major_formatter(yticks)

plt.hist(X1,bins =bins,weights= w,density=True,cumulative=True,histtype ="step",color ="b",edgecolor='r')
#可设置数据中每个数的权重，默认权重都为1
#density=True#归一化
#cumulative=True #累积

plt.xticks(bins)#可设置X轴的刻度线
plt.title("归一化的累积直方图示例",fontsize =18,color ="b")#可设置字的大小和颜色
plt.xlabel("x 轴标签",color ="b")
plt.ylabel("y 轴标签",color ="b")
plt.show()

128 篇文章23 人订阅

0 条评论