matplotlib(直方图,条形图,饼图,散点图)基础知识

import numpy as np

import pandas as pd

import matplotlib as mpl

import matplotlib.pyplot as plt

from pandas random import randn

from IPython.

%matplotlib inline

直方图:

hist()的参数
bins
可以是一个bin数量的整数值,也可以是表示bin的一个序列。默认值为10
range
bin的范围,当bins参数为序列时,此参数无效。范围外的值将被忽略掉,默认值为None
normed
如果值为True,直方图的值将进行归一化处理,形成概率密度,默认值为False
histtype
bar
默认为bar类型的直方图
barstacked
用于多种数据的堆叠直方图
step
创建未填充的线形图
stepfilled
创建默认填充的线形图
align
用于bin边界之间矩形条的居中设置。默认值为mid,其他值为left和right
color
指定直方图的颜色。可以是单一颜色值或颜色的序列。如果指定了多个数据集合,颜色序列将会设置为相同的顺序。如果未指定,将会使用一个默认的线条颜色
orientation
通过设置orientation为horizontal创建水平直方图。默认值为vertical

y=np.random.randn(1000)
x=np.arange(7)
ax=plt.gca()   #获取当前列表
ax.hist(y) 
ax.set_xlim(-3,3)
ax.set_xlabel('X')
ax.set_ylabel('y')
ax.set_title('first test of hist')

总结:直方图hist()内部只有一个参数y,用于显示某一输入数据的正态分布图

条形图:

条形图分为bar(),barh():水平条形图

plt.bar(left, height, width=0.8, bottom=None, hold=None, data=None, **kwargs)

left : sequence of scalars
    the x coordinates of the left sides of the bars    #设置为X的值

height : sequence of scalars
    the heights of the bars    #相当于y的值

bottom : scalar or array-like, optional
    the y coordinate(s) of the bars
    default: None    

例题:

1:#绘制有误差条的并列条形图
data1=10*np.random.rand(5)
data2=10*np.random.rand(5)
data3=10*np.random.rand(5)
e2=0.5*np.abs(np.random.randn(len(data2)))
locs=np.arange(1,len(data1)+1)
width=0.27
plt.bar(locs,data1,width=width)
plt.bar(locs+width,data2,yerr=e2,width=width,color='g')
plt.bar(locs+2*width,data3,width=width,color='r')
plt.xticks(locs+width*1.5,locs)

plt.show()

2:水平条形图

plt.barh([1,2,3],[3,2,5])  #水平条形图先y后x
plt.show()

plt.barh(bottom, width, height=0.8, left=None, hold=None, **kwargs)

bottom : scalar or array-like
    the y coordinate(s) of the bars  标量或类似数组的y座标

width : scalar or array-like
    the width(s) of the bars  


条形图总结:

1:条形图内部参数plt.bar(x轴,y轴,宽度)

其中X轴,Y轴类型为numpy.narray

2:水平条形图内部参数([y轴列表],[X轴列表])    水平条形图是先Y轴再由y轴来确定后面list的x座标

饼图 :

饼图 pie()  饼图适合展示各部分占总体的比例,
条形统计图适合比较各部分的大小

plt.figure(figsize=(4,4))#将饼图绘制在正方形区域内,用户解决正方形内部的椭圆
x=[45,35,20]#当各部分之和大于1时,会自动计算各部分占总体的百分比
labels=['cats','dogs','fishes']
plt.pie(x,labels=labels)  #labels参数可以设置各区域标签
plt.show()


y=[0.1,0.2,0.3]

labels=['cats','dogs','fishes']

plt.pie(y,labels=labels)

plt.show()


3:绘制一个由多层次的饼图

pie()参数:

1):X:饼图中所有元素所占的比例值或值(对于大于1会自动求其比例值)

2):labels:各个元素的标签

3):labeldistance:参数设置标签距离圆心的距离

4):autopct:参数比例值显示格式

5):pctdistance:参数设置比例值距离圆心的距离

6):explode:参数设置每一块距离圆心的距离

7):colors:参数设置每一块的颜色

8):shadow:为布尔值,是否设置阴影

9):startangle:指定圆弧开始绘制的角度

plt.figure(figsize=(4,4))

x=[4,9,21,55,30,18]
labels=['Swiss','Austria','spain','Italy','France','Benelux']
explode=[0.2,0.1,0,0,0.1,0]
colors=['r','k','b','m','c','g']

plt.pie(x,labels=labels,labeldistance=1.2,explode=explode,colors=colors,autopct='%1.1f%%',pctdistance=0.5,shadow=True)

plt.pie(x,labels=labels,labeldistance=1.2,explode=explode,colors=colors,autopct='%1.1f%%',pctdistance=0.5,shadow=True,startangle=67)

plt.show()





散点图:

x = np.random.randn(1000)


y1 = np.random.randn(len(x))

y2 = 1.2 + np.exp(x)


ax1 = plt.subplot(121)

plt.scatter(x,y1,color='indigo',alpha=0.3,edgecolors='white',label = 'no correl')

plt.xlabel('no correlation')

plt.grid(True)

plt.legend()


ax2 = plt.subplot(122)

plt.scatter(x,y2,color='green',alpha = 0.3,edgecolors='gray',label=' strong correlation')

plt.xlabel(''correl)

plt.grid(True)

plt.legend()

plt.show()


2:带有标记的线形图例

plt.figure(figsize=(4,4))

plt.plot(randn(5).cumsum(),'k-',label='one',marker='o')

plt.plot(randn(5),cumsum(),'k--',label='two')

plt.show()


2)data = randn(10).cumcum()


plt.figure(figsize=(4,4))

plt.plot(data,'k-',label = 'Default')

plt.plot(data,'k--',drawstyle = 'steps-post',label = 'steps-post')

plt.legend()


set_xticks 和set_xticklabels来修改X轴刻度

ax=plot.subplot(111)

ticks = ax.set_xticks([0,250,500,750,1000])

labels = ax.set_xticklabels(['one','two','three','four','five'],rotation =30,fontsize = 'small')

#rotation=30 设置下标刻度偏移角度

ax.set_title('My first matplotlib plot')

ax.set_xlabel('stage')



同样的设置y轴一样的道理:

只是将刻度x改成y:set_yticks() 和set_yticklabels()


yticks =ax.set_yticks([-40,-20,0,20,40])

ylabel = ax.set_yticklabels([-40,-20,0,20,40],rotation = 30,fontsize ='small')


ax.ylabel('ystage')

将图标保存为SVG文件:

plt.savefig()

例如:plt.savefig('figpath.png',dpi = 400,bbox_inches = 'tight')  #得到一张带有最小白边,且分辨率为400DPI的PNG图片

dpi:“每英寸点数”分辨率

bbox_inches:可以剪除当前图表周围的空白部分。tight:表示尝试剪除图表周围的空白部分。

通过文件扩展名,可以保存为任何图片形式

绘制图形:

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt


fig = plt.figure()
ax = fig.add_subplot(111)


rect = plt.Rectangle((0.2,0.75),0.4,0.15,color = 'k',alpha = 0.3)
circ = plt.Circle((0.7,0.2),0.2,color = 'b',alpha =0.3)
pgon = plt.Polygon([[0.15,0.2],[0.6,0.4],[0.7,0.2]],color ='y',alpha = 0.4)


ax.add_patch(rect)
ax.add_patch(circ)
ax.add_patch(pgon)





发布了39 篇原创文章 · 获赞 16 · 访问量 7万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章