How to solve a “matplotlib.backend_pdf” error?

  Kiến thức lập trình

I found this example code for creating pdf with python, but I got a error, show as follow. So I´ll like some help with this. I did a little research and try upgrade the matplotlib but the error keeps on the code.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backend_pdf import PdfPages
from pandas.plotting import table

datos = pd.read_csv('student-mat.csv')
datos['G1'].fillna(0, inplace = True)
df = pd.DataFrame(datos)
map = {'no':'no', 'si':'yes'}
etiquetas = ['no', 'si']
tags = ['Muy buena', 'Buena', 'Regular', 'Mala', 'Muy mal']

with PdfPages('nueva_prueba.pdf') as pdf:
    txt = 'Reporte Final'
    firstPage = plt.figure(figsize = (11.69, 8.27))
    firstPage.clf()
    firstPage.text(0.5, 0.5, txt, transform = firstPage.transFigure, size = 24, ha = 'center')
    pdf.savefig()
    pdf.close()

    txt_2 = 'Datos de la salud de los estudiantes'
    fig,ax = plt.subplots(1, 1)
    plt.gca().axis('off')
    plt.text(0, 1, txt_2, bbox = dict(boxstyle = 'square', color = 'grey'))
    plt.ioff()

    table(ax, np.round(df.health.describe(), 2), loc = 'center', colWidths = [0.2, 0.2, 0.2])
    pdf.savefig()
    pdf.close()

    df.paid.value_counts().plot(kind = 'pie', autopct = '%1.2f%%', shadow = True, startangle = 180,
                                fontsize = 12, pctdistance = 1.1, labeldistance = 1.4, labels = None)
    plt.legend(loc = 'best', labels = etiquetas)
    plt.ylabel('')
    plt.axis('equal')
    pdf.savefig()
    pdf.close()

    df.internet.value_counts().plot(kind = 'bar')
    plt.title('Internet')
    ax = plt.gca()
    ax.set_xticklabels(('Si', 'No'))
    pdf.savefig()
    pdf.close()

    ax = df['health'].value_counts().plot(kind = 'bar')
    ax.set_xticklabels(tags, rotation = 45, rotation_mode = 'anchor', ha = 'right')
    ax.text(0, 120, 'Buena salud', style = 'italic', bbox = {'facecolor':'red', 'alpha':0.5, 'pad':10})
    pdf.savefig()
    pdf.close()

ModuleNotFoundError                       Traceback (most recent call last)
Cell In[2], line 4
      2 import numpy as np
      3 import matplotlib.pyplot as plt
----> 4 from matplotlib.backend_pdf import PdfPages
      5 from pandas.plotting import table
      7 datos = pd.read_csv('student-mat.csv')

ModuleNotFoundError: No module named 'matplotlib.backend_pdf

I expected to have a pdf with different types of graphics, because I have a similar assignment from school.

LEAVE A COMMENT