过程是:边查文档边画图
分析如何画图:先画出那条线,之后在里面写好函数
过程
1,图中坐标轴不显示刻度:
如何画,搜一下坐标轴对象,axes有哪些相关方法:
参考网址:参考网址:https://matplotlib.org/api/pyplot_api
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon #生成多边形 的库
def func(x):
return -(x-2)*(x-8)+40
x=np.linspace(0,10)
y=func(x)
fig, ax=plt.subplots()
plt.plot(x,y,‘r’,linewidth=2)
a=2
b=9
ax.set_xticks([a,b])#设置坐标轴
ax.set_yticks([])
ax.set_xticklabels([’ a a a’,’ b b b’])#转义符
ix=np.linspace(a,b)#a到b之间的横坐标
iy=func(ix)
ixy=zip(ix,iy)#将图线上的坐标,合成坐标队
verts=[(a,0)]+list(ixy)+[(b,0)] #产生规则的数组
poly=Polygon(verts,facecolor=‘0.9’,edgecolor=‘0.5’) #生成poly对象,数字越大,颜色越浅
ax.add_patch(poly)
plt.figtext(0.9,0.05,’
x
x
x’)#x轴的标记,0.9和0.05 是x的位置
plt.figtext(0.1,0.9,’
y
y
y’)
#添加函数的数学公式
x_math=(a+b)*0.5
y_math=35
数学公式的位置
plt.text(x_math,y_math,r’
∫
a
b
(
−
(
x
−
2
)
∗
(
x
−
8
)
+
40
)
d
x
\int_a^b (-(x-2)*(x-8)+40)dx
∫ab(−(x−2)∗(x−8)+40)dx’,horizontalalignment=‘center’)#按照中间对齐
plt.ylim(ymin=25)#将位置y坐标调小一点
plt.show()
import numpy as np
import matplotlib.pyplot as plt
plt.style.use(‘ggplot’)#决定风格
x=np.random.randn(200)#随机生成200个随机数
y=x+np.random.randn(200)*0.5
#定义变量
margin_border=0.05
width=0.4
margin_between=0.05
height=0.2
#生成三个图的坐标轴
#主图
left_s=margin_border
bottom_s=margin_border
height_s=width
width_s=width
left_x=margin_border
bottom_x=margin_border+width+margin_between
height_x=height
width_x=width
left_y=margin_border+width+margin_between
bottom_y=margin_border
height_y=width
width_y=height
plt.figure(1,figsize=(8,8)) #生成一个8*8的画布
rect_s=[left_s,bottom_s,width_s,height_s]
rect_x=[left_x,bottom_x,width_x,height_x]
rect_y=[left_y,bottom_y,width_y,height_y]
axScatter=plt.axes(rect_s)
axHisX=plt.axes(rect_x)
axHisY=plt.axes(rect_y)
#去掉图一的x轴标注和图三的y轴标注
axHisX.set_xticks([])
axHisY.set_yticks([])
#画散点图
axScatter.scatter(x,y)
bin_width=0.25#柱状图宽度
xymax=np.max([np.max(np.fabs(x)),np.max(np.fabs(y))])#fab绝对值
lim=int(xymax/bin_width+1)*bin_width#得到图形精确宽度值
axScatter.set_xlim(-lim,lim)#对图形的x轴和y轴进行限制
axScatter.set_ylim(-lim,lim)
#画条形图
bins=np.arange(-lim,lim+bin_width,bin_width)#以bin_width为步长
axHisX.hist(x,bins=bins)
axHisY.hist(y,bins=bins,orientation=‘horizontal’)
#设置柱形图的坐标范围
axHisX.set_xlim(axScatter.get_xlim())
axHisY.set_ylim(axScatter.get_ylim() )
plt.show()