Search code examples
textmatplotlib

draw plot with lots of text outside of it (matplotlib)


I have 2 points (a vector of size 8) and 3 different bitwise operation (And, OR, XOR) I mapped each point and the result of bitwise operations on the 2D plot. I want to show each points real data itself and the result of operation beside my plot (right of the plot or above the plot (wherever is possible or it's better)) so later when I want to analysis the result I can read data value easily. right now my image is like this, and you can see the legend is cut off and I have no place outside of plot to write anything:

enter image description here

The text I want to show outside of my plot:

P1  P2  And Or  Xor     
0   1   0   1   1   
0   0   0   0   0   
0   0   0   0   0   
0   0   0   0   0   
1   1   1   1   0   
1   1   1   1   0   
1   1   1   1   0   
1   1   1   1   0   

The code I am using :

import numpy as np
import pylab as pl
fig = pl.figure()
ax = fig.add_subplot(111)
            
ax.plot(p1x, p1y, 'bx', label='Point 1', alpha=.55, markersize=30)
ax.plot(p2x, p2y, 'r+', label='Point 2', alpha=.55, markersize=30)
ax.plot(Andx, Andy, 'go', label='AND', alpha=.45, markersize=10) 
ax.plot(Orx, Ory, 'y<', label='OR', alpha=.45, markersize=10) 
ax.plot(Xorx, Xory, 'ks',  label='XOR', alpha=.45, markersize=10) 
ax.set_title('Bitwise Operation')
ax.set_xlabel('axis X')
ax.set_ylabel('axis Y')
ax.axis([-0.05, 1.05, -0.05, 1.05])
pl.legend(loc='lower left', bbox_to_anchor=(1.02, 0), borderaxespad=0)
pl.show()

Solution

  • You can use add_axes to directly control the size and location of your axes and then use text to add the text you want. For example:

    import numpy as np
    import pylab as pl
    fig = pl.figure()
    
    ax =  fig.add_axes([0.1, 0.2, 0.4, 0.4])
    
    ax.plot(.1, .2, 'bx', label='Point 1', alpha=.55, markersize=30)
    ax.plot(.2, .1, 'r+', label='Point 2', alpha=.55, markersize=30)
    ax.plot(.3, .2, 'go', label='AND', alpha=.45, markersize=10) 
    ax.plot(.1, .3, 'y<', label='OR', alpha=.45, markersize=10) 
    ax.plot(.1, .2, 'ks',  label='XOR', alpha=.45, markersize=10) 
    ax.set_title('Bitwise Operation')
    ax.set_xlabel('axis X')
    ax.set_ylabel('axis Y')
    ax.axis([-0.05, 1.05, -0.05, 1.05])
    pl.legend(loc='lower left', bbox_to_anchor=(1.02, 0), borderaxespad=0)
    
    data = ('P1  P2  And Or  Xor \n'
    '0   1   0   1   1   \n'
    '0   0   0   0   0   \n'
    '0   0   0   0   0   \n'
    '0   0   0   0   0   \n'
    '1   1   1   1   0   \n'
    '1   1   1   1   0   \n'
    '1   1   1   1   0   \n'
    '1   1   1   1   0   \n')
    
    pl.text(1.75,0,data)
    pl.show()
    

    plot with text outside of axis