如何使用matplotlib创建具有连续轴的图形

如何使用matplotlib创建具有连续轴的图形

本文介绍了如何使用matplotlib创建具有连续轴的图形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个交互式图形.我无法弄清楚如何绘制一个连续的二次图-就像您在轴上缩小/移动一样,方程式在那里绘制,而不仅仅是在2 x点之间绘制,所以它是连续的.

I'm trying to create an interactive graphs. I can't figure out how to plot a quadratic graph that is continuous - as in if you zoom out/move across the axes, the equation is plotted there, not just between 2 x points, so it's continuous.

到目前为止,我已经知道了.

I've got this so far.

import matplotlib.pyplot as plt

xcoord=[]
ycoord=[]

for x in range(0,10):
    y=(2*x)**2 + 2*x + 4
    xcoord.append(x)
    ycoord.append(y)

plt.plot(xcoord,ycoord)
plt.show()

推荐答案

Matplotlib不是绘制函数,而是点.当然,如果连续函数仅足够密集,则可以用点来近似它们.

Matplotlib is does not plot functions, but rather points. Of course any continuous function can be approximated by points if they are only dense enough.

放大图时确实会发生问题,在这种情况下,以前的密集点会散开,并且可以观察到多边形结构.相反,在缩小时,可能会发生该函数尚未在特定范围之外求值的情况,因此该图将大部分保持空白.

The problem indeed occurs when zooming into the plot, in which case formerly dense points will spread out and a polygonial structure will be observable. Inversely when zooming out, it may happen that the function has not been evaluated outside a specific range and hence the plot will stay mostly empty.

一种解决方案是在每次轴限制发生变化时评估函数,特别是在覆盖整个轴范围并具有与像素一样多的点的网格上.我们可以从图形尺寸和dpi找出像素数.

A solution is to evaluate the function each time the axis limits change, notably on a grid which covers the complete axis range and has as many points as there are pixels. We can find out the number of pixels from the figure size and dpi.

为显示效果,我在这里添加了一个低振幅的正弦函数.

To show the effect, I added a sinusodial function with a low amplitude here.

import numpy as np
import matplotlib.pyplot as plt

func = lambda x: (2*x)**2 + 2*x + -4 + 0.2*np.sin(x*20)

fig, ax = plt.subplots()
ax.axis([-8,8,-100,400])
line, = ax.plot([])

def update(evt=None):
    xmin,xmax = ax.get_xlim()
    npoints = fig.get_size_inches()[0]*fig.dpi
    x = np.linspace(xmin, xmax, npoints)
    y = func(x)
    line.set_data(x,y)
    fig.canvas.draw_idle()

ax.callbacks.connect('xlim_changed', update)
fig.canvas.mpl_connect("resize_event", update)
plt.show()

这篇关于如何使用matplotlib创建具有连续轴的图形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 19:14