清除matplotlib中的ax2

时间:2017-01-14 20:02:46

标签: python matplotlib

我试图使用matplotlib绘制两条不同比例的线条。 它当前正在工作,除非我运行我的代码时第二个Y轴在更新时混乱。

以下是我使用的代码:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.pyplot import cm 
from datetime import datetime
import numpy as np    
import matplotlib.animation as animation

def animate(i, fig, ax):
# Converter function
    datefunc = lambda x: mdates.date2num(datetime.strptime(x, '%d-%m-%Y_%H:%M:%S'))

    # Read data from 'file.dat'
    dates, levels, temp = np.genfromtxt('datosPlot.txt',    # Data to be read
                                        converters={0: datefunc}, # Formatting of column 0
                                        dtype=float,   # All values are floats
                                        usecols=(0,1,2), #Leer las tres primeras columnas de datos.txt
                                        unpack=True)   # Unpack to several variables

    # Configure x-ticks
    ax1.clear()

    ax1.set_xticks(dates) # Tickmark + label at every plotted point
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y %H:%M'))


    ax2 = ax1.twinx()

    fig.tight_layout()

fig = plt.figure()
ax1 = fig.add_subplot(111)
ani = animation.FuncAnimation(fig, animate, fargs=(fig, ax1), interval=1000)
plt.show() 

我的数据(datosPlot.txt)如下所示:

14-01-2017_14:01:16 1 16
14-01-2017_14:01:19 14 22
14-01-2017_14:01:22 2 17
14-01-2017_14:01:25 4 19
14-01-2017_14:01:28 6 24
14-01-2017_14:01:31 12 19
14-01-2017_14:01:34 4 18
14-01-2017_14:01:37 9 20

第一列是X轴(date_time),第二列是pH,第三列是温度。

我在调用ax2.clear()之前和之后尝试添加ax2 = ax1.twinx(),但它不起作用。我如何清除它,因为我可以使用ax1

以下是我不添加任何ax2.clear()时的情况: enter image description here

1 个答案:

答案 0 :(得分:3)

尝试在动画之外创建轴,并且只使用每个动画步骤中实际需要的代码。

以下是一个可运行的示例,您需要将函数em.genfromtxt()中的读取替换为对np.genfromtxt(....)的原始调用。

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime
import numpy as np    
import matplotlib.animation as animation


##### Emulator to generate data #########
class emulator():
    def __init__(self):
        self.dates = []
        self.levels = []
        self.temp = []

    def genfromtxt(self):
        self.dates.append(mdates.date2num(datetime.now()))
        self.levels.append(np.random.randint(1,14))
        self.temp.append(np.random.rand(1)*16+4)
        return self.dates, self.levels, self.temp

em = emulator()
##### End of Emulator to generate data #########




# Converter function
datefunc = lambda x: mdates.date2num(datetime.strptime(x, '%d-%m-%Y_%H:%M:%S'))


def animate(i):
    # Read data from 'file.dat'
    # instead we use an emulator here, replace with your original genfromtxt function
    dates, levels, temp = em.genfromtxt()

    # Configure x-ticks
    ax1.clear()
    ax2.clear()
    ax1.grid(True)
    ax2.grid(True)

    ax1.plot_date(dates, levels, ls='-', marker='.', color='red', label='pH')
    ax2.plot_date(dates, temp, ls='-', marker='.', color='blue', label='Temperatura C')

    ax1.set_xticks(dates) # Tickmark + label at every plotted point
    ax1.locator_params(axis='x',nbins=10)
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y %H:%M'))
    #Leyendas
    lines = ax1.get_lines() + ax2.get_lines()
    plt.legend(lines, [l.get_label() for l in lines], loc=2)

    fig.autofmt_xdate(rotation=45)
    fig.tight_layout()



fig = plt.figure()

# we create both axes outside the animation and already set those parameters
# which stay the same throughout the animation.
ax1 = fig.add_subplot(111)

ax1.set_title('pH y Temp')
ax1.set_ylabel('pH')

ax2 = ax1.twinx()  # This should happen outside the animation already.
ax2.set_ylabel('Temperatura C')    

ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()