matplotlib 使用
程序员文章站
2022-03-01 22:36:24
...
#coding=utf-8
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy.misc
from PIL import Image
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
np.set_printoptions(suppress=True)
'''
#MDA过滤异常值
def is_outlier(arr,threshold=3.5): #数据整体符合标准正太分布
if len(arr.shape)==1:
arr = arr[:,None]
median = np.median(arr)
diff = np.sum((arr-median)**2,axis=-1)
diff = np.sqrt(diff)
MDA = np.median(diff)
final_score = 0.6745*diff/MDA
#print (final_score)
return final_score>threshold
#np.random.seed(4)
#x = np.random.randn(100) #生成100个近似标准正太分布数据
#x = np.random.randint(4,100,10)
x = np.random.random(100) #生成100个0~1之间的浮点数
x = np.r_[x,5,4,1,2]
filters = x[~is_outlier(x)]
'''
#绘制箱线图剔除离散点
'''
plt.boxplot(x,0,'gx') #带x的就是离群值
plt.show()
'''
#打开图片
'''
pic = Image.open("Koala.jpg")
#转化为矩阵
pic_arr = np.array(pic.getdata()).reshape(pic.size[1],pic.size[0],3)
plt.imshow(pic_arr)
plt.colorbar()
plt.show()
'''
#线条属性
'''
y = [1,4,3,2,5,7]
plt.plot(y,c='red',lw=2.2,label='test',marker='D',ls='steps')
#ls有'--','-.',':','steps'
#marker有'>','<','+','*','o','D','h','_','8','p',','
plt.show()
'''
#自定义刻度
'''
axis = plt.gca()
axis.locator_params(tight=True,nbins=20)
plt.plot(np.random.normal(10,.1,100))
plt.show()
'''
#添加图例和注解
'''
x1 = np.random.normal(30,3,100)
x2 = np.random.normal(20,2,100)
x3 = np.random.normal(10,3,100)
plt.plot(x1,label='plot1')
plt.plot(x2,label='plot2')
plt.plot(x3,label='plot3')
#plt.legend(loc=0) #自动确定图例的位置
plt.legend(bbox_to_anchor=(0,1.02,1,0.102),loc=3,ncol=3,mode='expand')
#bbox_to_anchor是比例(0*xmax,1.02*ymax,1*xmax,0.102*ymax)
#为数据点设立注释
plt.annotate("string_value", (55,20),xytext=(5,38),arrowprops=dict(arrowstyle='->'))
plt.show()
'''
#将坐标轴移到中心
'''
x = np.linspace(-np.pi,np.pi,100)
y = np.sin(x)
axis = plt.gca()
axis.spines['right'].set_color('none')
axis.spines['top'].set_color('none')
axis.spines['bottom'].set_position(('data',0))
axis.spines['left'].set_position(('data',0))
axis.xaxis.set_ticks_position('bottom')
axis.yaxis.set_ticks_position('left')
plt.plot(x,y,label='sin')
plt.legend(loc=0)
plt.show()
'''
#绘制直方图
'''
x = np.random.normal(100,15,10000)
plt.hist(x,bins=50,alpha=0.3)
plt.show()
'''
#绘制条形图
'''
y = np.random.randint(3,10,8)
plt.barh(np.arange(8),y)
plt.yticks(np.arange(3), labels=['a','b','c'])
plt.show()
'''
#绘制饼图
'''
x = np.random.randint(20,100,5)
labels = ['a','b','c','d','e']
explode = [0.1,0,0,0,0]
plt.pie(x,explode=explode,labels=labels,autopct='%1.3f%%')
plt.show()
'''
#图形填充
'''
x = np.linspace(0,10,1000)
y1 = np.sin(x)
y2 = 1.5*np.cos(x)
plt.plot(x,y1,c='r',ls='--')
plt.plot(x,y2,c='b',ls='-.')
plt.fill_between(x, y1, y2, where=y2-0.5>y1,facecolor='darkblue')
plt.fill_between(x, y1, y2, where=y2<y1,facecolor='deeppink')
plt.show()
'''
#绘制散点图
'''
x = np.random.randn(1000)
y2 = 1.2+np.exp(x)
plt.scatter(x,y2,color='indigo',alpha=1,edgecolors='red')
plt.text(-1,4,"text",size=40)
plt.show()
'''
#绘制等高线图
'''
x = np.arange(-1.5,1.5,0.1)
y = np.arange(-1.5,1.5,0.1)
X,Y = np.meshgrid(x,y) #网格点
z = (1-X**2+Y**2)*np.exp((-Y)**3/3)
cs = plt.contour(z,np.arange(-1,1.5,0.3))
plt.clabel(cs,fmt='%1.1f',inline=True,fontsize=10)
plt.colorbar(cs)
plt.show()
'''
#绘制3D表面图形
'''
fig = plt.figure()
ax = fig.gca(projection="3d")
x = np.arange(-1.5,1.5,0.1)
y = np.arange(-1.5,1.5,0.1)
X,Y = np.meshgrid(x,y) #网格点
z = np.power(X,2)+np.power(Y,2)
ax.plot_surface(X,Y,z, cmap=plt.cm.coolwarm)
#ax.plot_wireframe(X,Y,z, cmap=plt.cm.coolwarm)
plt.show()
'''
#绘制3d散点图
'''
fig = plt.figure()
ax = fig.gca(projection='3d')
x=[1,3,5,8]
y=[2,8,9,6]
z=[2,4,5,3]
ax.plot(x,y,z)
#ax.scatter(x,y,z)
plt.show()
'''
#平面
'''
fig = plt.figure()
ax = fig.gca(projection="3d")
x = np.arange(1,10,0.1)
y = np.arange(1,10,0.1)
X,Y = np.meshgrid(x,y) #网格点
z = -(X/3-2/3*Y-8/3)
#也可以这样
#ax.plot(X.ravel(),Y.ravel(),z.ravel())
#ax.plot_wireframe(X,Y,z, cmap=plt.cm.coolwarm)
plt.show()
'''
#直线方程
'''
fig = plt.figure()
ax = fig.gca(projection="3d")
x = np.arange(1,10,0.1)
y = -(x-1)/4
z = -3*(x-1)/4-2
ax.plot(x,y,z)
#ax.plot_wireframe(X,Y,z, cmap=plt.cm.coolwarm)
plt.show()
'''
#应用
#直线方程
#两个坐标轴
'''
x = [5.51,5.69,5.82,5.94,6.05,6.16,6.28,6.36]
plt.bar(np.arange(0,len(x)*2,2),x,color='#EC5E33',label=u'用户规模')
plt.ylim(5,6.60)
label = ['2016Q1','2016Q2','2016Q3','2016Q4','2017Q1','2017Q2','2017Q3','2016Q4']
plt.xticks(np.arange(0,len(x)*2,2),labels=label)
plt.title(u"2016Q1~2017Q4中国手机新闻客户端用户规模")
for i in np.arange(len(x)):
plt.text(i*2-0.4,x[i]+0.01,x[i])
plt.twinx()
x1 = [0.038,0.033,0.023,0.021,0.019,0.018,0.020,0.013]
plt.plot(np.arange(0,len(x)*2,2),x1,color='r',label=u'增长率')
plt.ylim(0,0.04)
plt.legend(loc=0)
for i in np.arange(len(x)):
plt.text(i*2-0.4,x1[i], '%.1f%%'%(x1[i]*100))
plt.show()
'''
#横向条形图
'''
x=np.array([0.197,0.209,0.316,0.487,0.501])
x=x/np.sum(x)
plt.barh(np.arange(0,len(x)*2,2),x,color='#EC5E33')
label=['新浪新闻','天天快报','网易新闻','腾讯新闻','今日头条']
plt.yticks(np.arange(0,len(x)*2,2), labels=label)
for i in np.arange(len(x)):
plt.text(x[i],i*2, '%.1f%%'%(x[i]*100))
plt.title(u'2017年中国手机新闻客户端活跃用户top5')
plt.show()
plt.show()
'''
'''
data = [540367,595244,643974,689052,744127]
rate = [0.079,0.078,0.073,0.069,0.067]
plt.bar(np.arange(0,len(data)*2,2),data,color='#EC5E33')
plt.ylim(100000,800000)
for i in np.arange(len(data)):
plt.text(i*2-0.4,data[i],(data[i]))
plt.twinx()
plt.plot(np.arange(0,len(data)*2,2),rate,color='r',label=u'增长率')
for i in np.arange(len(rate)):
plt.text(i*2,rate[i], '%.1f%%'%(rate[i]*100))
plt.ylim(0,0.35)
plt.title(u'2013-2017年国内生产总值及增长率')
plt.legend(loc='upper left')
plt.show()
'''
#堆叠图
'''
data=np.array([[0.36,0.69,1],
[0.34,0.71,1],
[0.34,0.67,1],
[0.33,0.67,1]])
color_map=['#EC5E33','#FF69B4','#DA70D6']
for i in np.arange(3):
plt.bar(np.arange(0,8,2),data[:,2-i],color=color_map[2-i])
for j in range(4):
if(i!=0):
plt.text(j*2-0.2,data[j,i]-0.05,'%.1f%%'%((data[j,i]-data[j,i-1])*100))
else:
plt.text(j*2-0.2,data[j,i]-0.05,'%.1f%%'%(data[j,i]*100))
plt.xticks(np.arange(0,8,2), labels=['腾讯新闻','网易新闻','搜狐新闻','今日头条'])
plt.yticks([0.2,0.5,0.8],labels=['14-25岁','26-35岁','35岁以上'])
plt.title(u'新闻资讯App用户人群分析-年龄')
plt.show()
'''
''''
data=np.array([[0.16,0.44,1],
[0.17,0.52,1],
[0.13,0.41,1],
[0.20,0.48,1]])
color_map=['#EC5E33','#FF69B4','#DA70D6']
for i in np.arange(3):
plt.bar(np.arange(0,8,2),data[:,2-i],color=color_map[2-i])
for j in range(4):
if(i!=0):
plt.text(j*2-0.2,data[j,i]-0.05,'%.1f%%'%((data[j,i]-data[j,i-1])*100))
else:
plt.text(j*2-0.2,data[j,i]-0.05,'%.1f%%'%(data[j,i]*100))
plt.xticks(np.arange(0,8,2), labels=['腾讯新闻','网易新闻','搜狐新闻','今日头条'])
plt.yticks([0.1,0.3,0.7], labels=['一线城市','二线城市','三线城市'])
plt.title(u'新闻资讯App用户人群分析-地域')
plt.show()
'''