How do I plot multiple X or Y axes in matplotlib?

前端 未结 2 553
后悔当初
后悔当初 2020-12-23 21:35

I\'m currently using matplotlib to plot a measurement against 2 or 3 other measurements (sometimes categorical) on the x-axis. Currently, I am grouping the data on the x-axi

2条回答
  •  旧时难觅i
    2020-12-23 22:27

    Joe's example is good. I'll throw mine in too. I was working on it a few hours ago, but then had to run off to a meeting. It steals from here.

    import matplotlib.pyplot as plt
    import matplotlib.ticker as ticker
    
    ## the following two functions override the default behavior or twiny()
    def make_patch_spines_invisible(ax):
        ax.set_frame_on(True)
        ax.patch.set_visible(False)
        for sp in ax.spines.itervalues():
            sp.set_visible(False)
    
    def make_spine_invisible(ax, direction):
        if direction in ["right", "left"]:
            ax.yaxis.set_ticks_position(direction)
            ax.yaxis.set_label_position(direction)
        elif direction in ["top", "bottom"]:
            ax.xaxis.set_ticks_position(direction)
            ax.xaxis.set_label_position(direction)
        else:
            raise ValueError("Unknown Direction : %s" % (direction,))
    
        ax.spines[direction].set_visible(True)
    
    data = (('A',0.01),('A',0.02),('B',0.10),('B',0.20)) # fake data
    
    fig = plt.figure(1)
    sb = fig.add_subplot(111)
    sb.xaxis.set_major_locator(ticker.FixedLocator([0,1,2,3]))
    
    sb.plot([i[1] for i in data],"*",markersize=10)
    sb.set_xlabel("dose")
    
    plt.subplots_adjust(bottom=0.17) # make room on bottom
    
    par2 = sb.twiny() # create a second axes
    par2.spines["bottom"].set_position(("axes", -.1)) # move it down
    
    ## override the default behavior for a twiny axis
    make_patch_spines_invisible(par2) 
    make_spine_invisible(par2, "bottom")
    par2.set_xlabel("treatment")
    
    par2.plot([i[1] for i in data],"*",markersize=10) #redraw to put twiny on same scale
    par2.xaxis.set_major_locator(ticker.FixedLocator([0,1,2,3]))
    par2.xaxis.set_ticklabels([i[0] for i in data])
    
    plt.show()
    

    Produces:

    alt text

提交回复
热议问题