import matplotlib.pyplot as plt import numpy as np #step1 #用matplotlib.pyplot.figure()创建一个Figure个例 fig = plt.figure() #step 2 #Figure实例创建一个两行一列的绘图区,并同时在第一个位置创建了一个subplot ax = fig.add_subplot(2,1,1)#2rows,one column,first plot #step 3 #用Axes实例方法画一条线 t = np.arange(0.0,1.0,0.01) s = np.sin(2*np.pi*t) line, = ax.plot(t,s,color='blue',lw=2)
#设置Line2D的属性 x = range(0,5) y = [2,5,7,8,10] #1 直接在plot()函数中设置 plt.plot(x,y,linewidth=10);#设置线的粗细参数为10 #通过获得线对象,对线对象进行设置 line,=plt.plot(x,y,'-') line.set_antialiased(False) # 关闭抗锯齿功能 #获得线属性,使用setp()函数设置 lines = plt.plot(x, y) plt.setp(lines,color='r',linewidth=10)
#绘制line的方法 ## 1. pyplot方法绘制 import matplotlib.pyplot as plt x = range(0,5) y = [2,5,7,8,10] plt.plot(x,y); # 2. Line2D对象绘制 import matplotlib.pyplot as plt from matplotlib.lines import Line2D fig = plt.figure() ax = fig.add_subplot(111) line = Line2D(x, y) ax.add_line(line) ax.set_xlim(min(x), max(x)) ax.set_ylim(min(y), max(y)) plt.show()
import numpy as np import matplotlib.pyplot as plt fig = plt.figure() x = np.arange(10) y = 2.5 * np.sin(x / 20 * np.pi) yerr = np.linspace(0.05, 0.2, 10) plt.errorbar(x, y + 3, yerr=yerr, label='both limits (default)');
#hist绘制直方图 import matplotlib.pyplot as plt import numpy as np x=np.random.randint(0,100,100) #生成[0-100)之间的100个数据,即 数据集 bins=np.arange(0,101,10) #设置连续的边界值,即直方图的分布区间[0,10),[10,20)... plt.hist(x,bins,color='fuchsia',alpha=0.5)#alpha设置透明度,0为完全透明 plt.xlabel('scores') plt.ylabel('count') plt.xlim(0,100)#设置x轴分布范围 plt.show() #Rectangle矩形类绘制直方图 import pandas as pd import re df = pd.DataFrame(columns = ['data']) df.loc[:,'data'] = x df['fenzu'] = pd.cut(df['data'], bins=bins, right = False,include_lowest=True) df_cnt = df['fenzu'].value_counts().reset_index() df_cnt.loc[:,'mini'] = df_cnt['index'].astype(str).map(lambda x:re.findall('\[(.*)\,',x)[0]).astype(int) df_cnt.loc[:,'maxi'] = df_cnt['index'].astype(str).map(lambda x:re.findall('\,(.*)\)',x)[0]).astype(int) df_cnt.loc[:,'width'] = df_cnt['maxi']- df_cnt['mini'] df_cnt.sort_values('mini',ascending = True,inplace = True) df_cnt.reset_index(inplace = True,drop = True) #用Rectangle把hist绘制出来 import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(111) for i in df_cnt.index: rect = plt.Rectangle((df_cnt.loc[i,'mini'],0),df_cnt.loc[i,'width'],df_cnt.loc[i,'fenzu']) ax1.add_patch(rect) ax1.set_xlim(0, 100) ax1.set_ylim(0, 16) plt.show()