简体   繁体   中英

Second y scale repeating axis ticks

I have some code below which plots 3 sets of random numbers by adding them to a plot (simulating real world data gathered from say a temperature sensor). I am attempting to make 2 scales on the same plot.

Here, y2List is negative and this is the data set that I would like to create the second axis for. I figured out how to do this using other questions on here.

The problem is that when each data point is added, the second y axis ticks are shown again so that the second y axis is very crowded with numbers. I can get round this by setting a limit on the second y axis, which produces an image like this:

在此处输入图片说明

The second y axis is slightly darker than the others, and this is because python is plotting the same numbers on top of the existing ones after each point is plotted (I can tell because the numbers get darker as each point is plotted)

My question... is there a way to make the second y axis only plot the second scale only once? This is obviously just to make the plot aesthetically pleasing but every little helps!

My code is below:

plt.ion() # enable interactivity

def makeFig():

    ax.plot(xList, yList, color='blue', label='something1' if x == 0 else '')
    ax.plot(xList, y1List, color='red', label='something2' if x == 0 else '')
    ax2 = ax.twinx()
    ax2.plot(xList, y2List, color='orange', label='something else' if x == 0 else '')
    ax2.set_ylim(-20,0)

xList=list()
yList=list()
y1List=list()
y2List=list()

x=0
while x<11:

    fig1=plt.figure(1)
    ax = fig1.add_subplot(111)

    x_1 = datetime.datetime.now()
    date_formatter = DateFormatter('%H:%M:%S')

    y=np.random.random()
    y1=np.random.random() *3
    y2=np.random.random() *(-13)

    xList.append(x_1)
    yList.append(y)
    y1List.append(y1)
    y2List.append(y2)

    makeFig()
    plt.gcf().autofmt_xdate()
    ax = plt.gca()
    ax.xaxis.set_major_formatter(date_formatter)
    max_xticks = 10
    xloc = plt.MaxNLocator(max_xticks)
    ax.xaxis.set_major_locator(xloc)
    plt.get_current_fig_manager().window.wm_geometry("940x700+5+0")

    plt.draw()        
    plt.legend(loc=2, bbox_to_anchor=(1, 0.5), prop={'size':10})
    x+=1
    plt.pause(0.5)

You should move the creation of the figure and the twin axes outside of your loop. They only need to be done once.

Specifically, move fig1=plt.figure(1) , ax = fig1.add_subplot(111) and ax2 = ax.twinx() outside the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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