简体   繁体   English

如何动态更新matplotlib刻度标签

[英]How do I update matplotlib tick labels dynamically

I have an animated graph that gets Network usage history and scales the y limits dynamically depending on the magnitude of the relevant data being passed. 我有一个动画图,它获取网络使用历史并根据要传递的相关数据的大小动态缩放y限制。 How do I get my y tick labels to reflect the changing y limits? 如何获得我的y勾号标签以反映变化的y限制? Everything works fine when I set blit=Flase everything updates fine however I don't want everything to update every tick, just the y tick labels when the y limits change? 当我设置blit=Flase一切正常,但一切正常,但是我不希望所有变化都更新,仅当y限制发生变化时才更新y刻度标签? So how do I just update or redraw the y tick labels? 那么如何更新或重绘y刻度标签呢?

def resize(self, y_data):
    cur_max = max(y_data)
    if cur_max > self.ax.get_ylim()[1]:  # if cur_max > upper y limit..
        self.ax.set_ylim(-1, cur_max + cur_max * .10)  # increase upper y limit to fit cur_max
        ### update/redraw tick labels? ###
    if self.ax.get_ylim()[1] * .25 > cur_max > 0:  # if 1/4 the upper y limit > cur_max and cur_max > 0...
        self.ax.set_ylim(-1, cur_max * .50)  # set upper y limit 1/2 its current size
        ### update/redraw tick labels? ###

I guess what you need is to chose an appropriate tick locator and/or tick formatter : a function that is called to dynamically relocate the ticks and labels when the axis limits are changed. 我猜您需要的是选择一个合适的刻度定位器和/或刻度格式器:此功能可以在更改轴限制时动态地重新定位刻度和标签。

all docs can be found here : http://matplotlib.org/api/ticker_api.html 所有文档都可以在这里找到: http : //matplotlib.org/api/ticker_api.html

You can use predefined locators (eg LinearLocator) or define your own locator following the example below : 您可以使用预定义的定位器(例如LinearLocator)或按照以下示例定义自己的定位器:

import matplotlib.pyplot as plt
from matplotlib import ticker
import numpy as np

#- define the data
x = np.linspace(0., 1., 100)
y = np.random.randn(len(x))

#- plot it
ax = plt.gca()
ax.plot(x, y, 'k')

#- define your own locator based on ticker.LinearLocator
class MyLocator(ticker.LinearLocator):
   def tick_values(self, vmin, vmax):
       "vmin and vmax are the axis limits, return the tick locations here"
       return [vmin, 0.5 * (vmin + vmax), vmax]

#- initiate the locator and attach it to the current axis
ML = MyLocator()
ax.yaxis.set_major_locator(ML)

plt.show()
#- now, play with the zoom to see the y-ticks changing

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM