【2.2】柱形图(matplotlib-hist)

from numpy.random import normal
gaussian_numbers = normal(size=1000)
import matplotlib.pyplot as plt
from numpy.random import normal
gaussian_numbers = normal(size=1000)
plt.hist(gaussian_numbers)
plt.title("Gaussian Histogram")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()

png

#因为histogram默认是生成10个bin,有时候我们觉得区分细度不够的时候,可以人为来增加bin
plt.hist(gaussian_numbers, bins=20)
plt.show()

png

#我们也可以将纵坐标的频数转换成频率
plt.hist(gaussian_numbers, bins=20, normed=True)
plt.show()

png

#作累积概率分布图(cumulative distribution)
plt.hist(gaussian_numbers, bins=20, normed=True, cumulative=True)
plt.show()

png

#指定bin的横坐标范围
plt.hist(gaussian_numbers, bins=(-10,-1,1,10))
plt.show()

png

#未填充的bar
plt.hist(gaussian_numbers, bins=20, histtype='step')
plt.show()

png

二、更高级的用法

2.1 两个hist图的重叠

import matplotlib.pyplot as plt
from numpy.random import normal, uniform
gaussian_numbers = normal(size=1000)
uniform_numbers = uniform(low=-3, high=3, size=1000)
plt.hist(gaussian_numbers, bins=20, histtype='stepfilled', normed=True, color='b', label='Gaussian')
plt.hist(uniform_numbers, bins=20, histtype='stepfilled', normed=True, color='r', alpha=0.5, label='Uniform')
plt.title("Gaussian/Uniform Histogram")
plt.xlabel("Value")
plt.ylabel("Probability")
plt.legend()
plt.show()

png

2.2 x、y轴互换

import numpy as np
import matplotlib.pyplot as plt

data = np.random.exponential(1, 100)

# Showing the first plot.
plt.hist(data, bins=10)
plt.show()

# Cleaning the plot (useful if you want to draw new shapes without closing the figure
# but quite useless for this particular example. I put it here as an example).
plt.gcf().clear()

# Showing the plot with horizontal orientation
plt.hist(data, bins=10, orientation='horizontal')
plt.show()

# Cleaning the plot.
plt.gcf().clear()

# Showing the third plot with orizontal orientation and inverted y axis.
plt.hist(data, bins=10, orientation='horizontal')
plt.gca().invert_yaxis()
plt.show()

图1:

图2:

图3:

参考资料:

个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn

Sam avatar
About Sam
专注生物信息 专注转化医学