使用python matplotlib绘制简单图形

来源:互联网 发布:nginx静态资源缓存 编辑:程序博客网 时间:2024/06/08 06:07

1.直方图

#做直方图#使用hist函数,第一个参数bins为要分的多少面元,默认是10,我们设置的是20pop= np.random.randint(0,100,100)#产生100个0-100的随机数n,bins,patches = plt.hist(pop,bins=20,color='r')plt.title("M10")plt.show()

这里写图片描述

2.条状图

#条状图#横坐标是类别,不是数值,使用bar()函数绘制index = ['A','B','C','D','E']#np.arange(5)values = np.random.randint(1,10,5)plt.bar(index,values,alpha=0.7)#alpha透明度,范围0-1plt.title('M10')plt.legend(['First'])plt.show()

这里写图片描述

3.水平条状图

#使用barh函数index = ['A','B','C','D','E']values = np.random.randint(1,10,5)plt.barh(index,values,alpha=0.5,color='red')plt.title('M10')plt.legend(['Second'])plt.show()

这里写图片描述

4.dataframe

#为pandas DataFrame生成多序列条状图data = {    's1':[1,2,3,4,5],    's2':[2,4,3,5,1],    's3':[2,4,3,1,2]}df = pd.DataFrame(data)df.plot(kind='bar')#使用bar函数

这里写图片描述

5.多序列堆积条状图

#同样使用bai函数,设置属性值bottom为上一个index = np.arange(5)value1 = np.random.randint(1,10,5)value2 = np.random.randint(1,10,5)value3 = np.random.randint(1,10,5)plt.axis([0,5,0,30])plt.bar(index,value1,color='b')plt.bar(index,value2,bottom=value1,color='r')plt.bar(index,value3,bottom=value1+value2,color='g')plt.xticks(index,['A','B','C','D','E'])#第二个参数为第一个的对应值plt.show()

这里写图片描述

6.使用不同填充(非颜色)来区分

#使用hatch关键词index = np.arange(5)value1 = np.random.randint(1,10,5)value2 = np.random.randint(1,10,5)value3 = np.random.randint(1,10,5)plt.axis([0,5,0,30])plt.bar(index,value1,hatch='///')plt.bar(index,value2,bottom=value1,hatch='\\')plt.bar(index,value3,bottom=value1+value2,hatch='xx')plt.xticks(index,['A','B','C','D','E'])#第二个参数为第一个的对应值plt.show()

这里写图片描述

7.为pandas dataframe绘制堆积条状图只需要stacked关键词设置为Ture,即df.plot(kind='bar',stacked='True')

8.上下两排条形图

x = np.arange(8)y1 = np.random.randint(1,10,8)y2 = np.random.randint(1,10,8)plt.bar(x,y1,facecolor='y')#使用facecolor修改填充颜色plt.bar(x,-y2,facecolor='b')#使用-y2将其显示在下面plt.grid(True)#显示网格#显示条图的注释list_name=['p1','p2','p3','p4','p5','p6','p7','p8']for x1,y3 in zip(x,y1):    plt.text(x1-0.1,y3+0.2,list_name[x1])#前两个参数为位置for x,y in zip(x,y2):    plt.text(x-0.1,-y-0.5,list_name[x])plt.show()

这里写图片描述

9.标准饼图

#饼图labels = ['A','B','C','D','E']values = [10,20,23,43,54]clolor = ['y','g','r','black','b']#不定义的话系统自动分配plt.pie(values,labels=labels,colors=clolor)plt.axis('equal')#显示标准的圆plt.title('M10')plt.show()

这里写图片描述

10.突出饼图部分

#使用explode函数,范围0-1,表示抽离范围labels = ['A','B','C','D','E']values = [10,20,23,43,54]clolor = ['y','g','r','m','b']#不定义的话系统自动分配explode=[0.5,0,0,0,0]#抽离度#shadow添加效果,autopct添加百分比参数plt.pie(values,labels=labels,colors=clolor,explode=explode,shadow=True,autopct='%1.1f%%',startangle=180)#startangle表示旋转角度plt.axis('equal')#显示标准的圆plt.title('M10')plt.show()

这里写图片描述

原创粉丝点击