0

I try to add matrices in X-axis using matplotlib. The code I wrote is:

#!/bin/python

import sys
import numpy as np
import math
import decimal 
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab 
from matplotlib import rcParams

def plot():           
    N = 6
    ind = np.arange(N)
    ind_label = ['1X', '2X' , '3X' , '4X', '5X', '6X']

    y = [1.60, 1.65, 1.70, 1.75, 1.80]
    m1 = [1.62, 1.64, 1.64, 1.71, 1.7, 1.68]
    m2 = [1.61 , 1.7, 1.7, 1.8, 1.75, 1.75]
    m3 = [1.63 , 1.69, 1.7, 1.67, 1.64, 1.61]

    width = 0.2

    fig = plt.figure()
    ax = fig.add_subplot(111)

    rec_m1 = ax.bar(ind, m1, width, color='r', align='center')
    rec_m2 = ax.bar(ind+width, m2, width, color='g', align='center')
    rec_m3 = ax.bar(ind+width*2, m3, width, color='b', align='center')

    ax.set_ylabel('Value',fontsize=20)
    ax.set_xlabel('Matrix', fontsize=20)
    ax.tick_params(axis='both', labelsize=17)
    ax.set_xticks(ind+width)
    ax.set_xticklabels(ind_label, fontsize=18)
    ax.axis([-0.2, 5.6, 1.58, 1.82])

    ax.legend((rec_m1[0],rec_m2[0],rec_m3[0]),('Method 1','Method 2','Method 3'), loc="upper right",shadow=True)

    plt.grid()
    plt.tight_layout()
    plt.show()

if __name__ == '__main__':
    plot()

The current output figure is: https://i.sstatic.net/DJVxA.png

However, the most painful part is to add X-labels. I show the expected output in the figure. https://i.sstatic.net/b6h3U.png

I tried the method mentioned in this post How to display a matrix in the Matplotlib annotations .

But it does not work in my case. Any help or thoughts would be appreciated. Thanks a lot!

1 Answer 1

1

You were almost there; with the links provided in your question, you can solve it as follows:

ax.set_xticklabels([r"$\left[ \begin{array}{cc} 0 & 1 \\ 1 & 0 \end{array}\right]$",
                    r"$\left[ \begin{array}{cc} 0 & 1 \\ 5 & 0 \end{array}\right]$",
                    r"$\left[ \begin{array}{cc} 0 & 1 \\ 10 & 0 \end{array}\right]$",
                    r"$\left[ \begin{array}{cc} 0 & 1 \\ 30 & 0 \end{array}\right]$",
                    r"$\left[ \begin{array}{cc} 0 & 1 \\ 50 & 0 \end{array}\right]$",
                    r"$\left[ \begin{array}{cc} 0 & 1 \\ 100 & 0 \end{array}\right]$"])

The total code becomes:

#!/bin/python

import sys
import numpy as np
import math
import decimal
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
from matplotlib import rcParams

def plot():
    N = 6
    ind = np.arange(N)
    ind_label = ['1X', '2X' , '3X' , '4X', '5X', '6X']

    y = [1.60, 1.65, 1.70, 1.75, 1.80]
    m1 = [1.62, 1.64, 1.64, 1.71, 1.7, 1.68]
    m2 = [1.61 , 1.7, 1.7, 1.8, 1.75, 1.75]
    m3 = [1.63 , 1.69, 1.7, 1.67, 1.64, 1.61]

    width = 0.2

    rcParams['text.usetex'] = True
    fig = plt.figure()
    ax = fig.add_subplot(111)

    rec_m1 = ax.bar(ind, m1, width, color='r', align='center')
    rec_m2 = ax.bar(ind+width, m2, width, color='g', align='center')
    rec_m3 = ax.bar(ind+width*2, m3, width, color='b', align='center')

    ax.set_ylabel('Value',fontsize=20)
    ax.set_xlabel('Matrix', fontsize=20)
    ax.tick_params(axis='both', labelsize=17)
    ax.set_xticks(ind+width)
    ax.set_xticklabels(ind_label, fontsize=18)
    ax.axis([-0.2, 5.6, 1.58, 1.82])

    ax.legend((rec_m1[0],rec_m2[0],rec_m3[0]),('Method 1','Method 2','Method 3'), loc="upper right",\
shadow=True)
    ax.set_xticklabels([r"$\left[ \begin{array}{cc} 0 & 1 \\ 1 & 0 \end{array}\right]$",
                        r"$\left[ \begin{array}{cc} 0 & 1 \\ 5 & 0 \end{array}\right]$",
                        r"$\left[ \begin{array}{cc} 0 & 1 \\ 10 & 0 \end{array}\right]$",
                        r"$\left[ \begin{array}{cc} 0 & 1 \\ 30 & 0 \end{array}\right]$",
                        r"$\left[ \begin{array}{cc} 0 & 1 \\ 50 & 0 \end{array}\right]$",
                        r"$\left[ \begin{array}{cc} 0 & 1 \\ 100 & 0 \end{array}\right]$"])
    ax.xaxis.set_tick_params(pad=15)

    plt.grid()
    plt.tight_layout()
    plt.show()

if __name__ == '__main__':
    plot()

A few notes:

  • You will require LaTeX on your system.

  • This can take a while to render: this is because Matplotlib was developed to create high quality plots, plus the additional LaTeX rendering underneath for each label.

  • I have offset the tick labels using xaxis.set_tick_params(pad=15), because with the brackets around the matrix, the tick labels ended up inside the plot

  • They are probably ways (e.g. using more rcParams) to change the font size or the used LaTeX font.

The resulting figure is:

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot for your prompt help. Actually, some of my setting is wrong. And I got this error: raise ValueError: left cannot be >= right and raise ValueError('bottom cannot be >= top')... If I change to another host, then your code works like a charm. Thanks!
@Neverfaraway I wouldn't know about the error, but perhaps that host has an older version of numpy or matplotlib that's causing problems.
Thanks a lot for your help. I upgrade the numpy and matplotlib on my host, but the error is still there. It is so weird. I reported this issue at Matplotlib@Github. Hope they can have some insights on this error. Thanks again for your help.
You can also put the error as a question on SO. If you do so, do include the full traceback, so people can see where the error occurs. Include a small program that causes the error, and don't forget to identify your platform/OS in the question as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.