【问题标题】:Cannot get minor grid lines to appear in matplotlib figure无法在 matplotlib 图中出现次要网格线
【发布时间】:2013-11-25 06:30:50
【问题描述】:

好的,我有下面的代码,用于实时绘制来自通过串行接收的嵌入式设备的一些数据。它并不是一个生产工具,而是一个内部工程工具,因此它不是非常用户友好。问题是无论我做什么,我都无法出现次要网格线,即使在这里它们设置为True, which=both。我可以对主要网格线做任何我想做的事情,但未成年人不会出现。有任何想法吗?代码如下:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
import serial

SERIAL_PORT_NUM=9

...a bunch of constants...
#windows starts serial port numbers at 1, python starts at 0
SERIAL_PORT_NUM = SERIAL_PORT_NUM - 1
"""
Open the serial port
"""
ser =serial.Serial(port=SERIAL_PORT_NUM,baudrate=115200,bytesize=8,parity='N',stopbits=1,timeout=None,xonxoff=0,rtscts=0)

# First set up the figure, the axis, and the plot element we want to animate
raw_adc_fig = plt.figure()
raw_adc_ax = plt.axes(xlim=(0, 200), ylim=(0, 2047))
raw_adc_ax.grid(True, which='both')
raw_adc_fig.suptitle("Raw ADC data")
plt.ylabel("ADC values (hex)")
plt.xlabel("time (sec)")
raw_adc_line, = raw_adc_ax.plot([], [], lw=2)

def read_serial(serial_port):
    tmp = ''
    same_line = True
    while same_line:
        tmp += serial_port.read(1)
        if tmp != '':
            if tmp[-1] == '*':
                same_line = False
    tmp = tmp.rstrip()
    tmp = tmp.lstrip()
    return tmp

def process_serial(input_data):
    output_data = 0
    intermediate_data = input_data[A_TYPE_START_POS:A_TYPE_STOP_POS + 1]
    if( intermediate_data != ''):
        output_data =  int(intermediate_data , 16 )
    else:
        print "bad data"
        output_data = -100

    return output_data

def get_sound_value(serial_port):
    cur_line = ''

    get_next_line = True
    # read in the next line until a sound packet of type A is found
    while( get_next_line ):
        cur_line = read_serial(serial_port)
        if( (cur_line != '') and (cur_line[0:3] == ROUTER_SOUND_DATA) and (len(cur_line) == D_TYPE_STOP_POS + 2) ):
          get_next_line = False

    sound_value = process_serial(cur_line)
    return sound_value

# initialization function: plot the background of each frame
def raw_adc_init():
    raw_adc_line.set_data([], [])
    return raw_adc_line,

# animation function.  This is called sequentially
def raw_adc_animate(i):
    sound_data_list.append( get_sound_value(ser) )
    y = sound_data_list
    if( len(y) == 190 ):
        del y[0]
    x = np.linspace(0, len(y), len(y))
    raw_adc_line.set_data(x, y)
    return raw_adc_line,

# call the animator.  blit=True means only re-draw the parts that have changed.
raw_adc_anim = animation.FuncAnimation(raw_adc_fig, raw_adc_animate, init_func=raw_adc_init, frames=200, interval=1000, blit=True)

编辑:修复了打开串口的错误。将timeout=0 更改为timeout=None

【问题讨论】:

    标签: python numpy matplotlib pyserial graphing


    【解决方案1】:

    不幸的是,ax.grid 在这方面有点令人困惑。 (这是一个设计错误/常见问题。)它打开了次要网格,但次要刻度仍然关闭。

    除了拨打ax.grid(True, which='both')之外,您还需要拨打plt.minorticks_onax.minorticks_on

    【讨论】:

    • 你是绝对正确的。还值得注意的是,为了在次要刻度上获得标签,您需要以下几行:
    • raw_adc_ax.yaxis.set_minor_formatter(FormatStrFormatter("%3d")) raw_adc_ax.xaxis.set_minor_formatter(FormatStrFormatter("%4d")) 无法及时得到我的编辑...谢谢@joe-kington
    • 这个功能花了我 30 分钟的时间。谢谢先生帮助我。
    【解决方案2】:

    你应该使用plt.minorticks_on()

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig = plt.figure(1)
    ax = fig.add_subplot(111)
    
    x = np.linspace(0,10,41)
    y = np.sin(x)
    
    plt.plot(x,y)
    plt.grid(b=True, which='major', color='k', linestyle='-')
    plt.grid(b=True, which='minor', color='r', linestyle='-', alpha=0.2)
    plt.minorticks_on()
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-11
      • 2014-03-22
      • 1970-01-01
      • 2014-01-09
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      相关资源
      最近更新 更多