实战-函数积分图、散点条形图

实战

1)函数积分

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon#用Polygon需要导入patches

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])#给x传一个list a和b,此时x坐标上显示的是2和9

ax.set_yticks([])#让y的坐标轴显示空值,没有ticks

ax.set_xticklabels(['$a$','$b$'])#设置x的标签,加$是以数学公式的字体显示a和b

ix=np.linspace(a,b)#表示函数曲线上a到b的所有值
iy=func(ix)

ixy=zip(ix,iy)#把x和y以坐标对的形式写出来

verts=[(a,0)]+list(ixy)+[(b,0)] #a点,b点,和曲线上对应的点

poly=Polygon(verts,facecolor='0.9',edgecolor='0.5') #Polygon是多边形对象。生成poly对象,数字越大,颜色越浅,分别是边缘颜色和中间填充的颜色

ax.add_patch(poly)

plt.figtext(0.95,0.04,'$x$')#x轴(x字母的位置)标记的位置
plt.figtext(0.1,0.9,'$y$')

#添加函数的数学公式
x_math=(a+b)*0.5#准备把公式放在这个位置的横坐标x
y_math=35#准备把公式放在这个位置的纵坐标y

plt.text(x_math,y_math,r'$\int_a^b (-(x-2)*(x-8)+40)dx$',horizontalalignment='center')#公式查表得来的,用horizontalalignment='center'按照中间对齐,就不用前面的坐标了
plt.ylim(ymin=25)#将位置y坐标调小一点


plt.show()

在这里插入图片描述

2)散点条形图

效果图以及参数对应的位置画在图上的
在这里插入图片描述

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))])#求出离中心最远的点的坐标作为图的边界

lim=int(xymax/bin_width+1)*bin_width#得到图形精确宽度值

axScatter.set_xlim(-lim,lim)#对图形的x轴和y轴进行限制,设置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()

绘制结果:

在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值