3

I'm trying to use this tutorial (LINK) to create multipage-subplots of data frame groups. Each subplot is a patient. I used df.groupby("studyid")) to group each patient. The data of the patient is year (x-axis) and EDSS (disease score) on y-axis. In the plotting part, I'm trying to draw a line plot for each group.

import matplotlib.pyplot as plt
import numpy as np
import random
import seaborn as sns
import timeit

from matplotlib.backends.backend_pdf import PdfPages

# this erases labels for any blank plots on the last page
sns.set(font_scale=0.0)
m, n = 4, 6
datasize = 39 # 39 % (m*n) = 15, 24 (m*n) - 15 thus should result in 9 blank subplots on final page

fz = 7  # labels fontsize


def new_page(m, n):
    global splot_index
    splot_index = 0
    fig, axarr = plt.subplots(m, n, sharey="row")
    plt.subplots_adjust(hspace=0.5, wspace=0.15)
    arr_ij = [(x, y) for x, y in np.ndindex(axarr.shape)]
    subplots = [axarr[index] for index in arr_ij]
    for s, splot in enumerate(subplots):
        splot.grid(
            b=True,
            which="major",
            color="gray",
            linestyle="-",
            alpha=0.25,
            zorder=1,
            lw=0.5,
        )
        splot.set_ylim(0, 0.15)
        splot.set_xlim(0, 50)
        last_row = m * n - s < n + 1
        first_in_row = s % n == 0
        if last_row:
            splot.set_xlabel("X-axis label", labelpad=8, fontsize=fz)
        if first_in_row:
            splot.set_ylabel("Y-axis label", labelpad=8, fontsize=fz)
    return (fig, subplots)


with PdfPages("auto_subplotting_colors.pdf") as pdf:
    start_time = timeit.default_timer()
    fig, subplots = new_page(m, n)

    for sample in range(datasize):
            splot = subplots[splot_index]
            splot_index += 1    
            for year, group in grouped:
                splot.plot(group, x= "year", y="EDSS", linestyle="-", marker = "d", color="blue")
                splot.set_title("Sample {}".format(sample + 1), fontsize=fz)
                # tick fontsize & spacing
                splot.xaxis.set_tick_params(pad=4, labelsize=6)
                splot.yaxis.set_tick_params(pad=4, labelsize=6)

                # make new page:
                if splot_index == m * n:
                    pdf.savefig()
                    plt.close(fig)
                    fig, subplots = new_page(m, n)

    if splot_index > 0:
        pdf.savefig()
        plt.close(fig)

But I'm getting this error:

TypeError: plot got an unexpected keyword argument 'x'

How we should plot every group of groups in the subplots?

  • 1
    Your error is telling you that calling when calling `ax.plot()` you can never have `x=` (or `y=`). You need to pass those variables based on position. The first variable with be used as x values and the second as y values. The [documentation](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.plot.html) explains how to use `ax.plot`. – Jason Jun 11 '21 at 02:48

0 Answers0