python Matplotlib 绘制基础图形

1.使用plot()绘制折线图

示例:绘制一条正弦曲线

import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(0.1,10,100)
y=np.sin(x)
plt.plot(x,y,linestyle='-',linewidth=1,label='Sin() by plot()')
plt.legend()
plt.show()
如果x和y的对应关系是列表或元祖,则图形将呈现处折线效果 示例如下:
import matplotlib.pyplot as plt
import numpy as np
a=np.random.random((9,3))*2
y1=a[0:,1]
y2=a[0:,2]
x=np.arange(1,10)
print(x)
ax=plt.subplot(111)
width=10
hight=3
ax.axes.set_xlim(-0.5,width+0.2)
ax.axes.set_ylim(-0.5,hight+0.2)
plotdict={'dx':x,'dy':y1}
ax.plot('dx','dy','bD-',data=plotdict)
ax.plot(x,y2,'r^-')
plt.show(

2.使用bar() 绘制柱状图

示例:某公司4个部门一季度亏损情况的柱状图

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
#mpl.rcParams['font.sans-serif']=['STXINWEI.TTF']
x=['c','a','d','b']
y=[1,2,3,4]
plt.bar(x,y,alpha=0.5,width=0.3,color='yellow',edgecolor='red',
        label='The First Bar',lw=3)
plt.legend(loc='upper left')
plt.xticks(np.arange(4),('A','B','C','D'),rotation=30)
plt.yticks(np.arange(0,5,0.4))
plt.ylabel('Loss (10,000 yuan)',fontsize=10)
plt.xlabel('Department',fontsize=10)
plt.title('Losses of various departments in the first quarter',fontsize=10)
plt.tick_params(axis='both',labelsize=10)
plt.show()

3.堆积柱状图

import matplotlib.pyplot as plt
x=[1,3,5]
y=[3,8,9]
y1=[2,6,3]
y2=[1,1,1]
plt.bar(x,y,align='center',color='#66c2a5',tick_label=['A','B','C'],label='title_A')
plt.bar(x,y1,align='center',color='#8da0cb',tick_label=['A','B','C'],label='title_B')
plt.bar(x,y2,align='center',color='#8da0ae',tick_label=['A','B','C'],label='title_C')
plt.legend()
plt.show()

#多数据列
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(3)
y=[2,6,3]
y1=[6,10,4]
bar_width=0.4
tick_label=['A','B','C']
plt.bar(x,y,align='center',color='c',width=bar_width,label='title_A',alpha=0.5)
plt.bar(x+bar_width,y1,align='center',color='b',width=bar_width,label='title_B',alpha=0.5)
plt.xticks(x+bar_width/2,tick_label)
plt.legend()
plt.show()

 当需要在同一幅图形中同时显示横轴在两个指标下取值时,也可以使用bar()绘制水平线下方向的倒影柱状图 示例如下:

#倒影
import matplotlib.pyplot as plt
import numpy as np
n=12
X=np.arange(n)
Y1=(1-X/float(n))*np.random.uniform(0.5,1.0,n)
Y2=(1-X/float(n))*np.random.uniform(0.5,1.0,n)
plt.bar(X,+Y1,facecolor='#9966ff',edgecolor='white')
plt.bar(X,-Y2,facecolor='#ff9966',edgecolor='white')
plt.xlim(-.5,n)
plt.ylim(-1.25,1.25)
for x,y in zip(X,Y1):
        plt.text(x,y+0.05,'%.2f'%y,ha='center',va='bottom')
for x,y in zip(X,Y2):
        plt.text(x,-y-0.05,'%.2f'%y,ha='center',va='top')
print(Y1)
print(Y2)
plt.show()

4.使用barh()绘制条形图

import matplotlib.pyplot as plt
import numpy as np
x=np.arange(4)
y=[6,10,4,5]
y1=[2,6,3,8]
bar_width=0.4
tick_label=['A','B','C','D']
plt.barh(x,y,bar_width,align='center',color='c',label='title_A',alpha=1)
plt.barh(x+bar_width,y1,bar_width,align='center',color='b',label='title_B',alpha=1)
plt.yticks(x+bar_width/2,tick_label)
plt.legend()
plt.show()

5.使用hist()绘制直方图

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
from scipy.stats import norm
mu=100
sigma=15
x=mu+sigma*np.random.randn(10000)
fig,ax=plt.subplots()
n,bins,patches=ax.hist(x,50,density=1,facecolor='blue',alpha=0.3)
y=norm.pdf(bins,mu,sigma)
ax=plt.plot(bins,y,'--')
print(patches)
plt.show()

堆积直方图:

import matplotlib.pyplot as plt
import numpy as np
x1=np.random.randint(1,100,100)
x2=np.random.randint(0,100,100)
x=[x1,x2]
colors=['#fc8d62','#66c2a5']
labels=['A','B']
bins=range(1,101,10)
plt.hist(x,bins=bins,color=colors,histtype='bar',rwidth=10,label=labels,edgecolor='k')
plt.show()

6.使用pie()绘制饼图

import matplotlib.pyplot as plt
labels=['A-part','B-part','C-part','D-part']
nums=[0.25,0.15,0.36,0.24]
colors=['#377eb8','#4daf4a','#984ea3','#ff7f00']
explode=(0.1,0.1,0.1,0.1)
plt.pie(nums,explode=explode,labels=labels,autopct='%.2f%%',startangle=45
        ,shadow=True,colors=colors)
plt.title('The profit composition of each department in the first quarter')
plt.show()

 稍微变形 pie()函数还可以绘制嵌套的环形图 示例如下:

import matplotlib.pyplot as plt
labels=['A','B','C','D','E']
nums1=[29,19,22,18,12]
nums2=[22,27,18,11,22]
colors=['#e41a1c','#377eb8','#4daf4a','#984ea3','#ff7f00']
w1,t1,a1=plt.pie(nums1,autopct='%.1f%%',radius=1,pctdistance=0.85,
                 colors=colors,textprops=dict(color='w'),wedgeprops=dict(width=0.3,edgecolor='r'))
w2,t2,a2=plt.pie(nums2,autopct='%.1f%%',radius=0.7,pctdistance=0.75,
                 colors=colors,textprops=dict(color='w'),wedgeprops=dict(width=0.3,edgecolor='w'))
plt.setp(a1,size=8,weight='bold')
plt.setp(a2,size=8,weight='bold')
plt.setp(t1,size=8,weight='bold')
print(w1)
print(t1)
print(a1)
plt.show()

7.使用polar()绘制雷达图

import numpy as np
import matplotlib.pyplot as plt
labels=np.array(['a','b','c','d','e','f'])
dataLenth=6
data=np.array([2,4,3,6,5,8])
angles=np.linspace(0,2*np.pi,dataLenth,endpoint=False)
print(angles)
data=np.concatenate((data,[data[0]]))
angles=np.concatenate((angles,[angles[0]]))
print(data)
plt.polar(angles,data,'ro-',linewidth=2)
plt.thetagrids(angles*180/np.pi,labels)
plt.fill(angles,data,facecolor='y',alpha=0.25)
plt.ylim(0,10)
plt.show()

8.使用scatter()绘制散点图

import numpy as np
import matplotlib.pyplot as plt
x1=np.random.randn(20)
x2=np.random.randn(20)
colors=np.random.rand(20)
area=(30*np.random.rand(10))**2
plt.figure(1)
plt.plot(x1,'bo',markersize=20)
plt.plot(x2,'ro',ms=10)
# plt.scatter(x1,x2,s=area,c=colors)
plt.show()

9.使用stem()绘制棉棒图

import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(0,10,20)
y=np.random.randn(20)
print(y)
plt.stem(x,y,linefmt='-',markerfmt='*',basefmt='-')
plt.show()

10.使用boxplot()绘制箱线图

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df=pd.DataFrame(np.random.rand(8,5),columns=['A','B','C','D','E'])
df.boxplot()
print(df)
plt.show()

11.使用errorbar()绘制误差棒图

import numpy as np
from matplotlib import pyplot as plt
from scipy.stats import t
X=np.random.randint(5,15,15)
n=X.size
X_mean=np.mean(X)
X_std=np.std(X)
X_se=X_std/np.sqrt(n)
print(X_mean)
print(X_std)
print(X_se)
dof=n-1
alpha=1.0-0.95
conf_interval=t.ppf(1-alpha/2.,dof)*X_std*np.sqrt(1.+1./n)
fig=plt.gca()
plt.errorbar(1,X_mean,yerr=X_std,fmt='-s')
plt.errorbar(2,X_mean,yerr=X_se,fmt='-s')
plt.errorbar(3,X_mean,yerr=conf_interval,fmt='-s')
plt.xlim([0,4])
plt.ylim(X_mean-conf_interval-2,X_mean+conf_interval+2)
plt.tick_params(axis='both',which='both',bottom=False,top=False,
                labelbottom=True,left=True,right=False,labelleft=True)
plt.show()

可以结合柱状图:

import matplotlib.pyplot as plt
mean_values=[1,2,3]
variance=[0.2,0.4,0.5]
bar_labels=['bar 1','bar 2','bar 3']
fig=plt.gca()
x_pos=list(range(len(bar_labels)))
plt.bar(x_pos,mean_values,yerr=variance,align='center',alpha=0.5)
max_y=max(zip(mean_values,variance))
plt.ylim([0,(max_y[0]+max_y[1])*1.1])
plt.xticks(x_pos,bar_labels)
plt.tick_params(axis='both',which='both',bottom=False,top=False,
                labelbottom=True,left=True,right=False,labelleft=True)
plt.show()

12.使用stackplot()绘制堆积折线图

import numpy as np
import matplotlib.pyplot as plt
x=[1,2,3,4,5]
y1=[1,1,2,3,5]
y2=[0,4,2,6,8]
y3=[1,3,5,7,9]
y=np.vstack([y1,y2,y3])
labels=['Fibonacci','Evens','Odds']
fig,ax=plt.subplots()
ax.stackplot(x,y1,y2,y3,labels=labels)
ax.legend(loc='upper right')
# plt.stackplot(x,y1,y2,y3,labels=labels)
plt.show()

13.使用broken_barh()绘制间断条形图

import matplotlib.pyplot as plt
fig,ax=plt.subplots()
ax.broken_barh([(110,30),(150,10)],(10,9),facecolors='blue')
ax.broken_barh([(10,50),(100,20),(130,10)],(20,9),facecolors=('red','cyan','green'))
ax.set_ylim(5,35)
ax.set_xlim(0,180)
ax.set_yticks([15,25])
ax.set_yticklabels(['A','B'])
ax.grid(True)
plt.show()

14.使用step() 绘制阶梯图

import numpy as np
from numpy import ma
import matplotlib.pyplot as plt
x=np.arange(1,7,0.4)
print(x)
y=np.sin(x)+2.5
print(y)
plt.step(x,y,label='pre')
y-=0.5
plt.step(x,y,where='mid',label='mid')
y-=0.5
plt.step(x,y,where='post',label='post')
plt.legend()
plt.xlim(0,7)
plt.ylim(0,4)
plt.show()

 以上就是matplotlib的基本图形 欢迎大家一起学习讨论 thanks!

  • 0
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

要不要长胖_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值