[Python基础] 2.Matplotlib:绘图,可视化的必备

版权声明:Hello https://blog.csdn.net/Edward_is_1ncredible/article/details/81907563
import numpy as np
import matplotlib.pyplot as plt

I.绘图及设置
x = np.linspace(-np.pi,np.pi,256,endpoint=True)  # 设定x轴的范围,点的个数,点的个数越多越平滑
c = np.cos(x)
s = np.sin(x)
plt.figure()  # 设定画布
plt.title("COS & SIN")  # 设定抬头
plt.plot(x,c,color="blue",linewidth=1.0,linestyle="-",label="cos",alpha=0.5)  # 画图并设置样式
plt.plot(x,s,color="red",linestyle="--",label="sin")
plt.legend(loc="upper left")  # 设置图例的位置
plt.grid()  # 设置网格线
# gca为轴的编辑器
ax = plt.gca()
ax.spines["right"].set_color("none")  # 设置边界的颜色
ax.spines["top"].set_color("none")
ax.spines["left"].set_position(("data",0))  # 设置边界的位置
ax.spines["bottom"].set_position(("data",0))
ax.xaxis.set_ticks_position("bottom")  # 设置标签的位置
ax.yaxis.set_ticks_position("left")
plt.yticks(np.linspace(-1,1,5,endpoint=True))  # 设置y轴的范围
# for label in ax.get_xlabel()+ax.get_ylabel():
#     label.set_fontsize(188)
#     label.set_bbox(dict(facecolor="white",edgecolor="none",alpha=0))
plt.axis([-1,1,-0.5,1])  # 设定显示范围
plt.fill_between(x,np.abs(x)<0.5,c,c>0.5,color="green",alpha=0.5)  # 填充
# 辅助线的添加对应:横轴方向的位置,纵轴方向的位置,颜色,宽度,线形
t = 0.75
plt.plot([t,t],[0,np.cos(t)],"black",linewidth=1.5,linestyle="--")
# 辅助点的标记,对应:名称,位置(数字或者上述t均可),偏离,相对偏离,箭头类型,箭头弧度
# https://blog.csdn.net/u013457382/article/details/50956459 参考文档
plt.annotate("cos(0.75)",xy=(0.75,np.cos(t)),xycoords="data",xytext=(+10,+30),textcoords="offset points",
             arrowprops=dict(arrowstyle="->",connectionstyle="arc3,rad=.2"))

II.其他图的画法
fig=plt.figure()  # 设置画布
1.散点图
fig.add_subplot(3,3,1)
n = 128
X = np.random.normal(0,1,n)
Y = np.random.normal(0,1,n)
plt.xlim(-1.5,1.5),plt.xlim(-1.5,1.5)  # 设置x,y的范围
plt.xticks(),plt.yticks()  # 设置轴标签
plt.axis()  # 设定图内容的显示范围
plt.title("Scatter")
plt.xlabel("x"),plt.ylabel("y")  # 设置横纵坐标的名称
T = np.arctan2(Y,X)  # 设置颜色
plt.scatter(X,Y,s=75,c=T,alpha=0.5)  # 画图,s点的大小,c点的颜色,alpha透明度
2.柱状图
fig.add_subplot(3,3,2)
n = 10
X = np.arange(10)
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="#9999ff",edgecolor="black")
plt.bar(X,-Y2,facecolor="#ff9999",edgecolor="white")
# 设置并添加注释
for x,y in zip(X,Y1):
    plt.text(x+0.4,y+0.05,"%2f"%y,ha="center",va="bottom",size=6)
for x,y in zip(X,Y2):
    plt.text(x+0.4,-y-0.05,"%2f"%y,ha="center",va="top")
3.饼图
fig.add_subplot(3,3,3)
# 设定Z,等分,最后一个占2份
n = 20
Z = np.ones(n)
Z[-1] *= 2
# 画图,数据源,分离程度,颜色,标签
plt.pie(Z,explode=Z*0.05,colors=['%f'%(i/float(n)) for i in range(n)],
        labels=['%.2f'%(i/float(n)) for i in range(n)])
plt.gca().set_aspect("equal")  # 让图是一个正的圆形
plt.xticks([]),plt.yticks([])
4.极坐标
fig.add_subplot(3,3,4,polar=True)
n = 20
theta = np.arange(0.0,2*np.pi,2*np.pi/n)
radii = 10*np.random.rand(n)
plt.polar(theta,radii)
5.热图
fig.add_subplot(3,3,5)
from matplotlib import cm
data = np.random.rand(3,3) # 设定数据
cmap = cm.Blues  # 颜色设定并画图,aspect:自动调整
map = plt.imshow(data,cmap=cmap,aspect="auto",vmin=0,vmax=1)
6.3D图
from mpl_toolkits.mplot3d import Axes3D
ax = fig.add_subplot(3,3,6,projection="3d")
ax.scatter(1,1,3,s=100)
7.热力图
fig.add_subplot(3,1,3)
def f(x,y):
    return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
n = 256
x = np.linspace(-3,3,n)
y = np.linspace(-3,3,n)
X,Y = np.meshgrid(x,y)
plt.contourf(X,Y,f(X,Y),8,alpha=0.75,cmap=plt.cm.hot)

plt.show()

猜你喜欢

转载自blog.csdn.net/Edward_is_1ncredible/article/details/81907563