Adding caption below X-axis for a scatter plot using matplotlib

前端 未结 5 1048
灰色年华
灰色年华 2021-02-07 03:17

I am pretty new to python and to the matplotlib library. I have created a scatter plot using matplotlib and now I wish to add caption a little below the X-axis. This is my code:

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-07 04:01

    First, I feel weird posting an answer against the co-lead developer of matplotlib. Obviously, @tacaswell knows matplotlib far better than I ever will. But at the same time, his answer wasn't dynamic enough for me. I needed a caption that would always be based on the position of the xlabel, and couldn't just use text annotations.

    I considered simply changing the xlabel to add a newline and the caption text, but that wouldn't clearly differentiate the caption, and you can't do things like change the text size or make it italic in the middle of a text string.

    I solved this by using matplotlib's TeX capabilities. Here's my solution:

    from matplotlib import pyplot as plt
    from matplotlib import rc
    import numpy as np
    from pylab import *
    
    rc('text', usetex=True)
    
    file = open('distribution.txt', 'r')
    
    txt="I need the caption to be present a little below X-axis"
    
    x=[]
    y=[]
    for line in file:
        new=line.rstrip()
        mystring=new.split("\t")
        x.append(mystring[0])
        y.append(mystring[1])
    
    
    fig = plt.figure()
    ax1 = fig.add_axes((0.1,0.4,0.8,0.5))
    ax1.set_title("This is my title")
    ax1.set_xlabel(r'\begin{center}X-axis\\*\textit{\small{' + txt + r'}}\end{center}')
    ax1.set_ylabel('Y-axis')
    ax1.scatter(x,y, c='r')
    plt.xlim(0, 1.05)
    plt.ylim(0, 2.5)
    plt.show()
    

    I did the same thing with the random scatter plot from tacaswell's answer, and here's my result:

    One warning: if you tweak this to take input string variables, the strings may not be properly escaped for use with TeX. Escaping LaTeX code is already covered on Stack Overflow, at https://stackoverflow.com/a/25875504/1404311 . I used that directly, and then could take arbitrary xlabels and captions.

提交回复
热议问题