# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
from scipy import optimize
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号
ax = plt.gca()
#去掉边框
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
#移位置 设为原点相交
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
# 数据
mu = 100 # mean of distribution
sigma = 15 # standard deviation of distribution
x = mu + sigma * np.random.randn(10000)
percentage = 0.95
num_bins = 20
cnt = plt.hist(x, num_bins, normed=1, facecolor='blue', alpha=0.5, cumulative=True)
x = []
y = []
for index in range(len(cnt[1])):
if index != 0:
x.append(cnt[1][index])
for index in range(len(cnt[0])):
y.append(cnt[0][index])
plt.plot(x, y, "red")
x_per = []
y_per = []
for index in range(len(y)):
if y[index] > 0.95:
y_per.append(y[index-1])
y_per.append(y[index])
x_per.append(x[index-1])
x_per.append(x[index])
break
a = (y_per[1]-y_per[0])/(x_per[1]-x_per[0])
b = y_per[1]-a*x_per[1]
y_label = percentage
x_label = (y_label-b)/a
print(x_label)
print(y_label)
x1 = np.linspace(0, x_label, 50)
y1 = x1*0+percentage
plt.plot(x1, y1, "r--")
plt.xlabel('品位')
plt.ylabel('累计频率')
plt.title(r'品位频率累积分布直方图')
# Tweak spacing to prevent clipping of ylabel
plt.show()
效果如下:
关键代码如下:
ax = plt.gca()
#去掉边框
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
#移位置 设为原点相交
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))