(1) 使用linspace函数定义x为0.5到3.5之间产生的100个数据,y = sin(x),绘制曲线,如图蓝色线条;
(2) 使用random函数定义y1表示随机产生的100个数,绘制散点,如图蓝色星花;
(3) 使用xlim和ylim函数,显示x轴区间为(0,4),y轴区间为(-3,3);
(4) 显示x、y轴标签;
(5) 显示网格线;
(6) 绘制水平参考线,如图红色线条;
(7) 绘制竖直参考区间,如图黄绿色区域;
(8) 绘制水平参考区域,如图绿色区域;
(9) 绘制指向型文本注释,如图蓝色字体,maximum;
(10) 绘制无指向型文本注释,如图蓝色字体,y=sin(x);
(11) 添加title及文本标签图例。
import numpy as np
import math
import matplotlib.pyplot as plt
x = np.linspace(0.5, 3.5, 100)
y = np.sin(x)
y1 = np.random.uniform(-10,10, 100)
t = np.linspace(-10, 10, 100)
sig = 1 / (1 + np.exp(-t))
ax=plt.gca()
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False) # 撤掉上右边框
plt.axvspan(xmin=1.0,xmax=3.0,facecolor="y",alpha=0.3) # 横参考区间 v
plt.axhspan(ymin=0.0,ymax=1.0,facecolor="g",alpha=0.2)
plt.axhline(y=0.5,xmin=0.5, color="red", linestyle="--") # 画出参考线
plt.plot(x, y, linewidth=2, linestyle="-.") # , label=r"$y = sin(x)$"没label被警告 # 画出函数
plt.scatter(x,y1,marker='*')
plt.xlim(0, 4)
plt.ylim(-3, 3) # 限定坐标轴范围
plt.xlabel("x_axis")
plt.ylabel("y_axis") #坐标轴命名
plt.title("y = sin(x)") # 图像命名
plt.grid(color='pink', linestyle='--', linewidth=1) # 显示网格线
# plt.legend(fontsize=14) # 设置label字体大小
plt.annotate("y = sin(x)", xy = (3.3, 0), xytext=(0, 0), textcoords='offset points', color='b') #标记
plt.annotate('maximum', color= "blue",xy=(1.6, 1), xytext=(2.6, 0.6), arrowprops=dict(color='blue', shrink=0.05,headwidth =2.5,width = 0.5))
plt.show() # 显示图像
1、 使用bar()绘制柱形图、barh()绘制条形图,箱子编号为’sahfdaksj’,对应的箱子重量为[3, 1, 4, 5, 6, 8, 9, 7, 2]
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams["font.sans-serif"]=["SimHei"]
mpl.rcParams["axes.unicode_minus"]=False
# some simple data
x = [i for i in range(1,10)]
y = [3,1,4,5,6,8,9,7,2]
# create bar
plt.figure()
label = list("sahfdaksj")
plt.bar(x,y,align="center",color="c",tick_label=label,hatch="/")
# set x,y_axis label
plt.xlabel("箱子编号")
plt.ylabel("箱子重量")
plt.show()
plt.barh(x,y,align="center",color="c",tick_label=label,hatch="/")
# set x,y_axis label
plt.xlabel("箱子重量")
plt.ylabel("箱子编号")
plt.show()
2、 使用bar()绘制堆积柱形图和并列柱形图,堆积图中,y1 = [2, 4, 1, 6, 3]、 y2 = [6, 2, 3, 5, 1],并列图中,y1 = [2, 4, 1, 6, 3]、y2 = [6, 2, 3, 5, 1]
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(5)
y1 = np.array([2,4,1,6,3])
y2 = np.array([6,2,3,5,1])
plt.bar(x,y1)
plt.bar(x,y2,bottom=y1)
plt.legend(["class A","class B"])
plt.show()
width = 0.3
tick_label = ["A", "B", "C", "D", "E"]
plt.bar(x, y1, width, align="center", color="b", label="class A", alpha=0.5)
plt.bar(x+width, y2, width, align="center", color="r", label="class B", alpha=0.5)
plt.xticks(x+width/2, tick_label)
plt.legend()
plt.show()
3、 hist()绘制直方图,随机产生100个整数,步长为10,利用直方图,统计落入每个范围的数据个数,效果如下图:
num=np.random.randint(0,11,100)
plt.hist(num,color="red",alpha=0.7,rwidth= 0.5)
4、 hist()绘制堆积直方图,两个班的成绩分别是随机产生的100个(0,100)内的数,统计步长为10,颜色自定义
num1=np.random.randint(0,101,100)
num2=np.random.randint(0,101,100)
n=plt.hist(num1,bins=10,color="blue",alpha=0.5,rwidth= 0.5,range=(num1.min(),num1.max()))
plt.hist(num2,bins=10,color="purple",alpha=0.5,rwidth= 0.5,range=(num1.min(),num1.max()),bottom=n[0])
plt.legend(["class A","class B"])
plt.show()
5、 使用pie()绘制饼图和分列式饼图,类别为’简易箱’, ‘保鲜箱’, ‘行李箱’, ‘密封箱’,对应的占比为[0.05, 0.45, 0.15, 0.35],颜色自定义,图2中四个类别分裂的程度均为0.1
import matplotlib.pyplot as plt
kinds = ["简易箱", "保险箱", "行李箱","密封箱",]
colors = ["#e41a1c","#377eb8","#4daf4a","#984ea3"]
nums = [0.05,0.45,0.15,0.35]
plt.pie(nums,labels=kinds,autopct="%3.1f%%",startangle=60,colors=colors,labeldistance=1.1)
plt.legend(loc=1,bbox_to_anchor=(1, 0.5, 0.5, 0.5))
plt.show()
explode = [0.1]*4
plt.pie(nums,labels=kinds,autopct="%3.1f%%",explode= explode,startangle=60,colors=colors,labeldistance=1.1)
plt.legend(loc=4,bbox_to_anchor=(1, 0, 0.5, 0.5),title ="占比")
plt.show()
6、 使用scatter()绘制散点气泡图,随机产生100个点(x,y表示点的横纵坐标),s=(10x+20y)2表示气泡的大小,绘制气泡图
N = 100
x = np.random.randn(N)
y = np.random.randn(N)
s=(10*x+20*y)**2
plt.scatter(x,y,s)
7、 使用stem()绘制棉棒图,随机产生20个数,x采用linspace()在(0.5, 2* pi)之间产生20个数,y随机产生20个整数,绘制棉棒图
x = np.linspace(0.5,2 * np.pi,20)
y = np.random.randn(20)
plt.stem(x,y,linefmt = '-.',use_line_collection=False,label="stem fig")
plt.legend()
plt.show()
8、 使用boxplot()绘制箱线图,随机产生2组数据,每组数据均有5000个整数,颜色可自定义,绘制箱线图
box = plt.boxplot(x= np.random.normal(0,1, size=(5000,2)), patch_artist=True, labels=['随机生成器-1', '随机生成器-2'],widths=0.6)
colors = ['brown', 'green']
for patch,color in zip(box["boxes"],colors):
patch.set_color(color)
plt.ylabel("随机数值") #坐标轴命名
plt.title("随机数生成器抗干扰能力的稳定性比较")
9、 使用errorbar()绘制误差棒图,x从(0.1,0.6)之间产生6个数,y=ex,误差图效果
x = np.linspace(0.1,0.6,6)
y = np.exp(x)
plt.errorbar(x,y,fmt="bo",yerr=0.2,xerr=0.02)
plt.xlim(0,0.7)
plt.show()
10、 绘制带误差棒的柱形图,柱形图高度为[100, 82, 39, 92,43]对应的误差分别为[7, 2, 6, 10, 5],颜色自定义
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["font.family"] = "FangSong"
nums = [100, 82, 39, 92,43]
x= range(0,len(nums))
nums_SD = [7, 2, 6, 10, 5]
x_ticks = ["A","B","C","D","E"]
plt.xticks(x,x_ticks)
plt.bar(x, nums, yerr = nums_SD,capsize=3)
plt.title("不同芒果园种植区的单日收割量")
plt.xlabel("芒果种植园区")
plt.ylabel("收割量")
plt.grid(axis="y",linestyle=':', linewidth=2,alpha=0.7)
plt.show()
11、 使用step()绘制阶梯图,x从(0,10)之间产生的20个数,绘制y=sin(x)曲线,然后分别在该曲线前面和后面产生阶梯
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,10,0.5)
y = np.sin(x)
plt.plot(x, y, color='b', alpha=0.7,label='y=sin(x)')
plt.step(x, y , label='y=sin(x)-pre',color="y")
plt.step(x, y, where='mid', label='y=sin(x)-mid',color="g")
plt.step(x, y, where='post', label='y=sin(x)-post',color="r")
plt.legend(loc=1,bbox_to_anchor=(1, 0.5, 0.5, 0.5))
plt.show()
12、 使用stackplot()绘制堆积折线图(面积图),x=[1,2,3,4,5],y0=[0,3,4,2,5],y1=[2,4,1,6,3],y2=[6,2,3,5,1],颜色自定义
import numpy as np
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y1 = [0, 3, 4, 2, 5]
y2 = [2, 4, 1, 6, 3]
y3 = [6, 2, 3, 5, 1]
labels = ["Blue", "Orange", "Green"]
plt.stackplot(x, y1, y2, y3, labels=labels)
plt.legend(bbox_to_anchor=(0.8, 0.5, 0.5, 0.5))
plt.show()