python matploblib学习笔记

import matplotlib.pyplot as plt
import numpy as np

# matplotlib画图注释中文需要设置
from matplotlib.font_manager import FontProperties
xy_font_set = FontProperties(fname=r"c:windowsfonts方正稚艺简体.ttf", size=12)
zhushi_font_set = FontProperties(fname=r"c:windowsfonts方正粗倩简体.ttf", size=12)
titleYW_font_set = FontProperties(fname=r"c:windowsfontsGabriola.ttf", size=20)
titleZW_font_set = FontProperties(fname=r"c:windowsfonts汉仪细行楷简.ttf", size=18)

plt.figure()
# 两行两列的方格放第1个放个中
plt.subplot(2, 2, 1)
x = np.linspace(-5, 5, 50)
y1 = np.sin(x)
y2 = np.cos(x)

# line1加','是为了放入handles中
line1, = plt.plot(x, y1, color='green', linewidth=1.0, linestyle='--')
line2, = plt.plot(x, y2, color='blue', linewidth=1.0, linestyle='-')

# 设置A,B线条的标注并打印下来//handle指放入legend中的线条,labels给线条取名字,loc取legend位置
plt.legend(handles=[line1, line2], labels=['sin(x)', 'cos(x)'], loc='best')
# 设置x轴的取值范围
plt.xlim((-5, 5))
# 设置y轴的取值范围
# plt.ylim((-0.5,0.5))

# 设置坐标标签
plt.xlabel(u'电流/安培', fontproperties=xy_font_set)
plt.ylabel(u'电压/伏特', fontproperties=xy_font_set)

# 设置图表标题
plt.title(u'实验1--A,B线路的电流电压关系图', fontproperties=xy_font_set, size=20)

# 标注x,y轴刻度,并进行注释
new_ticks = np.linspace(-5, 5, 10)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-0.5, 0, 0.5], [u'低压:-0.5伏', u'安全:0伏', u'高压:0.5伏'], size=8, fontproperties=zhushi_font_set, color='grey')

# 抽取图,对其进行操作
ax = plt.gca()
print(ax)
# 设置四边,隐藏上右
# ax.spines['right'].set_color('none')
# ax.spines['top'].set_color('none')

# 设置四边的位置
# ax.spines['bottom'].set_position(('data',0)) //'axes'定位在y的相对多少的位置
# ax.spines['left'].set_position(('data',0))

# 添加标注
x0 = 0.25
y0 = np.sin(x0)
diya = -0.5
anquan = 0
gaoya = 0.5
# scatter代表散点,可用于画图
plt.scatter(x0, y0, s=30, color='purple')

# 描绘虚线从,注释线
plt.plot([-5, 5], [diya, diya], color='grey', linewidth=0.8, linestyle='--')
plt.plot([-5, 5], [anquan, anquan], color='grey', linewidth=0.8, linestyle='--')
plt.plot([-5, 5], [gaoya, gaoya], color='grey', linewidth=0.8, linestyle='--')

# 在某个点做注释
plt.annotate('x='+str(round(x0, 2))+','+'y='+str(round(y0, 2)), xy=(x0, y0), xycoords='data', xytext=(x0+0.08, y0-0.1))
plt.annotate('safe point', xy=(x0, y0), xycoords='data', xytext=(x0-0.08, y0+0.1), color='r', alpha=0.8)

# 展示网格线
plt.grid(True)

# 用scatter函数绘画随机的散点图
# 两行两列的方格放第2个放个中
plt.subplot(2, 2, 2)
n = 100
X = np.random.normal(0, 1, n) # 正态分布,0为均值,1为方差
Y = np.random.normal(0, 1, n)
# X=np.random.binomial() # 二项分布
T = np.arctan2(X, Y) # 给点予随机的颜色
plt.scatter(X, Y, s=75, c=T, alpha=0.5)

# 用bar函数绘制柱状图
# 两行两列的方格放第3个放个中
plt.subplot(2, 2, 3)
n = 2
xb = np.arange(n)
yb = 100*np.random.randn(2)**2
plt.xticks(np.arange(n), [u'A线路', u'B线路'], fontproperties=zhushi_font_set, color='grey', size=15)
plt.ylabel(u'电费/美元', fontproperties=xy_font_set)
plt.xlim(-1, 2)
plt.title(u'A、B线路的电费', fontproperties=xy_font_set, size=20)
plt.bar(xb, yb, facecolor='#9999ff', edgecolor='white')
# 对每个柱状图的值进行标注
for x, y in zip(xb, yb):
plt.text(x, y, str(round(y, 2))+u'美元', ha='center', va='bottom', fontproperties=zhushi_font_set, color='r', alpha=0.8)

# contourf函数进行等高线图绘制,contour函数加上等高线,clabel给每条线加标签
# 两行两列的方格放第4个放个中
plt.subplot(2, 2, 4)
x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)
x, y = np.meshgrid(x, y) # 把x, y组合起来,底部
z = (x**2-y**2)
plt.contourf(x, y, z, 8, alpha=0.8, cmap=plt.cm.hot)
C = plt.contour(x, y, z, 8, linewidth=0.5, colors='black')
plt.clabel(C, inline=True, fontsize=10, fontproperties=xy_font_set)
plt.xticks(()) # 去掉标签,坐标
plt.yticks(())

# 3维画图
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure() # 定义一个figure
ax = Axes3D(fig) # 抽取出fig
x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)
x, y = np.meshgrid(x, y) # 把x, y组合起来,底部
z = (x**2-y**2)
ax.plot_surface(x, y, z, cmap=plt.get_cmap('rainbow'), rstride=1, cstride=1) # cmap颜色组,rs为格子大小
ax.contourf(x, y, z, zdir='z', cmap='rainbow', offset=-25) # zdir设置投影到哪个轴面,offset投影的坐标面, 做等高线用
ax.contour(x, y, z, 18, linewidth=0.5, colors='black', offset=-25) # 8代表等高线要分割多少部分
#ax.set_zlim(-2, 2) # 设置z的范围



# subplot函数多图合一

# A histogram 绘制分布图
n = [1,3,3,4,5,4,6,7,8,5,2,1]
fig, axes = plt.subplots(1, 2, figsize=(12,4))
axes[0].grid(True)
axes[0].hist(n, bins=8)
axes[0].set_title(u"数字的分布",fontproperties=xy_font_set, size=20)
axes[0].set_xlim((min(n), max(n)))

# 积累
axes[1].grid(True)
axes[1].hist(n, cumulative=True, bins=8)
axes[1].set_title("Cumulative detailed histogram")
axes[1].set_xlim((min(n), max(n)));

# 饼状图

import matplotlib.pyplot as plt
fig=plt.figure()
labels='frogs','hogs','dogs','logs'
sizes=1,1,2,1
colors='yellowgreen','gold','lightskyblue','lightcoral'
explode=0,0.1,0,0
plt.pie(sizes,explode=explode,labels=labels,colors=colors,autopct='%1.1f%%',shadow=True,startangle=50)
plt.axis('equal')


# # 绘制特定的密度图,查看各个等级的乘客年龄分布
# plt.figure()
# data_train.Age[data_train.Pclass == 1].plot(kind='kde')
# data_train.Age[data_train.Pclass == 2].plot(kind='kde')
# data_train.Age[data_train.Pclass == 3].plot(kind='kde')
# plt.xlabel(u"Age", fontproperties=zhushi_font_set)
# plt.ylabel(u"Density", fontproperties=zhushi_font_set)
# plt.title(u"各等级的乘客年龄分布", fontproperties=xy_font_set, size=20)
# plt.legend((u'头等舱', u'2等舱', u'3等舱'), loc='best', prop=xy_font_set) # prop字体形式参数

# colspan = 2,代表该格的跨度,相当于合并右边的格
# Pclass_0_1.plot(kind='bar', stacked=True)
# 无敌的df自带plot函数,还不用自己fugure,标签下标都帮你画好了。stacked=True代表合并起来。
# plt.grid(True, linestyle="--", color="green", alpha=0.5) # 设置网格
plt.show()
原文地址:https://www.cnblogs.com/hirokuh/p/9335198.html