利用python绘制叠置的直方图,将多个直方图绘制在一起。
原始数据形式为:
结果为:
代码为:
# -*- coding: utf-8 -*-
"""
author:cz
e-mail:chinesevoice@163.com
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#select one sheet of excel
sheet = "Sheet1"
#assume that there are several plots in one sheet
start_num = 1
data = pd.read_excel('testdata.xlsx',sheet_name=sheet)
index = [[0,1],[2,3],[4,5],[6,7]]
X1 = data.iloc[:,index[start_num-1][0]]
X2 = data.iloc[:,index[start_num-1][1]]
#find proper intervals of bins
x_max = X1.max() if X1.max() > X2.max() else X2.max()
x_min = X1.min() if X1.min() < X2.min() else X2.min()
plt.figure(figsize=(8, 8))
plt.tick_params(labelsize=25)
bins = np.linspace(x_min, x_max, 30)
#find proper y limitation
bmax_x1 = X1.value_counts(bins=bins).max()
bmax_x2 = X2.value_counts(bins=bins).max()
bmax = bmax_x1 if bmax_x1 > bmax_x2 else bmax_x2
plt.hist(X2, bins, alpha = 0.7, facecolor="#f1afa3",edgecolor="#FF0000", label='col1')
plt.hist(X1, bins, alpha = 0.7, facecolor="#9eaef7",edgecolor="#0000FF", label='col2')
plt.legend(loc='upper right',fontsize=25)
# plt.legend(loc='upper left',fontsize=25)
plt.xlabel('bins (unit)',fontsize=25)
plt.ylabel('Frequency',fontsize=25)
plt.text(-0.075,bmax+bmax/50,"item{}".format(start_num),fontsize=25)
plt.ylim(0,bmax+bmax/10)
# plt.savefig(sheet+"_SDD{}.png".format(start_num))
plt.show()
任何问题可联系邮箱:
chinesevoice@163.com
转自:“科研萌新”微信公众号
如有侵权,请联系本站删除!