matplotlib相关代码
fried_chicken · · 算法·理论
饼图
import matplotlib.pyplot as plt
labels=['apple','banana','cherry','data']
sizes=[15,30,40,10]
colors=['gold','yellowgreen','lightcoral','lightblue']
explode=(0,0.1,0,0)
plt.pie(sizes,explode=explode,labels=labels,colors=colors,autopct='%1.1f%%',shadow=True,startangle=90)
plt.axis('equal')#确保饼图是圆的
plt.title("pie chart")
plt.show()
散点图
import random
import matplotlib.pyplot as plt
x=[random.randint(1,100) for _ in range(50)]
y=[random.randint(1,100) for _ in range(50)]
plt.scatter(x,y,c=x,cmap="viridis")
plt.title("sandiantu")
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.show()
折线图
import matplotlib.pyplot as plt
x=[8,10,12,14,16]
y1=[15,18,19,29,17]
y2=[10,13,14,17,12]
plt.plot(x,y1,label="shanodng",color="red")
plt.plot(x,y2,label="beijing",color="green")
plt.title("title")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.legend()
plt.show()
柱状图
import matplotlib.pyplot as plt
categroies=['A','B','C','D','E']
values=[20,40,35,30,10]
colors=["red","yellow","green","orange","purple"]
plt.bar(categroies,values,color=colors)#barh
plt.title('bar plot')
plt.xlabel('x-value')
plt.ylabel('y-value')
plt.show()
三维散点图
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
x=np.random.rand(100)
y=np.random.rand(100)
z=np.random.rand(100)
#设置3d图形
fig=plt.figure()
#创建一个3D子图
ax=fig.add_subplot(111,projection='3d')
#绘制3d散点图
ax.scatter(x,y,z,c='r',marker='o')
ax.set_xlabel('X label')
ax.set_ylabel('Y label')
ax.set_zlabel('Z label')
plt.title('3d scatter plot')
plt.show()
等高线
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-5,5,100)
y=np.linspace(-5,5,100)
x,y=np.meshgrid(x,y)
z=np.sin(x**2+y**2)
plt.contour(x,y,z,20,camp='RdGy')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
2d密度图
import matplotlib.pyplot as plt
import numpy as np
#当散点图数据量非常大的时候,点就会堆叠在一起,此时密度图可以更好的展示数据分布
x=np.random.normal(0,1,10000)
y=np.random.normal(0,1,10000)
plt.hexbin(x,y,gridsize=50,cmap='viridis',mincnt=1)#只显示密度大于一的区域
plt.colorbar(label='count')
plt.title("2D Denisty plot")
plt.xlabel('x')
plt.ylabel('y')
plt.show()
小提琴图
import matplotlib.pyplot as plt
import numpy as np
#小提琴图结合了箱线图和密度估计图,展示了数据分布,中位数、上下四分位数、最大值、最小值
#生成多组随机数据
data=[np.random.normal(0,std,100) for std in range(1,5)]
plt.violinplot(data,showmeans=True,showmedians=True)
plt.title("violin plot")
plt.xlabel('x')
plt.ylabel('y')
plt.xticks([1,2,3,4],['Group1','Group2','Group3','Group4'])
plt.show()
气泡图
#气泡图:多变量散点图,可以显示不同变量之间的相关性
import matplotlib.pyplot as plt
import numpy as np
x=np.random.rand(50)*10
y=np.random.rand(50)*10
size=np.random.rand(50)*1000+100
color=np.random.rand(50)
plt.scatter(x,y,s=size,c=color,cmap='plasma',alpha=0.7)
plt.colorbar(label='Colorbar')
plt.title('bubblechart')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
注释和箭头
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(0,10,50)
y=np.sin(x)
plt.plot(x,y)
plt.title("sine wave")
plt.xlabel("X")
plt.ylabel("Y")
plt.annotate('local max',xy=(2,0.5),xytext=(3,0.8),arrowprops=dict(facecolor='black',shrink=0.05))
plt.show()
极坐标
import matplotlib.pyplot as plt
import numpy as np
#极坐标图:以角度和半径表示数据,常用于周期性的数据
theta=np.linspace(0,2*np.pi,100)
r=np.sin(theta*2)+np.cos(theta*3)
fig=plt.figure()
ax=fig.add_subplot(111,projection='polar')#创建极坐标子图
ax.plot(theta,r,color='blue',linewidth=2.0,alpha=0.5)
ax.set_title('polar plot')
plt.show()
决策树
#决策树可视化与特征的重要性,加载鸢尾花数据集并且训练决策树模型。可视化决策树的结构,展示模型如何分类决策
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import plot_tree
iris=load_iris()
X=iris.data
Y=iris.target
#训练模型
model=DecisionTreeClassifier(max_depth=3)
model.fit(X,Y)
#创建图形
fig,(ax1,ax2)=plt.subplots(1,2,figsize=(15,6))
#可视化决策树的结构
plot_tree(model,filled=True,ax=ax1,feature_names=iris.feature_names,class_names=iris.target_names)
ax1.set_title('Decision Tree')
#可视化决策的重要性
importances=model.feature_importances_
feature_names=iris.feature_names
ax2.bar(feature_names,importances,color='skyblue')
ax2.set_title('feature importance')
ax2.set_ylabel('importance')
ax2.set_xlabel('feature')
ax2.tick_params(axis='x',rotation=90)
plt.tight_layout()
plt.show()
动画图表
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
#创建一个空白的图和轴
fig,ax=plt.subplots()
xdata,ydata=[],[]
line,=ax.plot(xdata,ydata,'r-')
#定义动画函数
def init():
ax.set_xlim(0,2*np.pi)
ax.set_ylim(-1,1)
return line,
def update(frame):
xdata.append(frame)
ydata.append(np.sin(frame))
line.set_data(xdata,ydata)
return line,
ani=FuncAnimation(fig,update,frames=np.linspace(0,2*np.pi,128),init_func=init,blit=True)
plt.title('sine wave')
plt.show()