0

I am trying to plot PrettyTable inside a matplotlib. Here is my code:

import numpy as np
import matplotlib.pyplot as plt
from prettytable import PrettyTable


myTable = PrettyTable(["Student Name", "Class", "Section", "Percentage"])
  
# Add rows
myTable.add_row(["Leanord", "X", "B", "91.2 %"])
myTable.add_row(["Penny", "X", "C", "63.5 %"])
myTable.add_row(["Howard", "X", "A", "90.23 %"])
myTable.add_row(["Bernadette", "X", "D", "92.7 %"])
myTable.add_row(["Sheldon", "X", "A", "98.2 %"])
myTable.add_row(["Raj", "X", "B", "88.1 %"])
myTable.add_row(["Amy", "X", "B", "95.0 %"])


points = np.linspace(-5, 5, 256)
y1 = np.tanh(points) + 0.5
y2 = np.sin(points) - 0.2

fig, axe = plt.subplots( dpi=300)
axe.plot(points, y1)
axe.plot(points, y2)
axe.legend(["tanh", "sin"])
axe.text(-10.5, 0.5, myTable)
plt.plot()

This code produces a plot which looks like this: enter image description here

How can do it so that the prettytable always remains centered above the plot without distorting the plot.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Slartibartfast
  • 1,058
  • 4
  • 26
  • 60
  • 1
    Seems like you need https://matplotlib.org/stable/gallery/misc/table_demo.html#sphx-glr-gallery-misc-table-demo-py – Trenton McKinney Sep 14 '21 at 20:38
  • 1
    if you insist on using prettytable instead of matplotlib's builtin table functions, you probably want to display it using a monospaced font so it doesn't get all misaligned – tmdavison Sep 14 '21 at 20:47

1 Answers1

1

use table function

import numpy as np
import matplotlib.pyplot as plt
from prettytable import PrettyTable
import pandas as pd

myTable = PrettyTable(["Student Name", "Class", "Section", "Percentage"])


# Add rows
myTable.add_row(["Leanord", "X", "B", "91.2 %"])
myTable.add_row(["Penny", "X", "C", "63.5 %"])
myTable.add_row(["Howard", "X", "A", "90.23 %"])
myTable.add_row(["Bernadette", "X", "D", "92.7 %"])
myTable.add_row(["Sheldon", "X", "A", "98.2 %"])
myTable.add_row(["Raj", "X", "B", "88.1 %"])
myTable.add_row(["Amy", "X", "B", "95.0 %"])

# your base plots
points = np.linspace(-5, 5, 256)
y1 = np.tanh(points) + 0.5
y2 = np.sin(points) - 0.2

plt.subplot(2, 1, 1)
plt.plot(points, y1)
plt.plot(points, y2)
plt.legend(["tanh", "sin"])
plt.plot()

# the table
plt.subplot(2, 1, 2)
df = pd.DataFrame.from_records(myTable.rows, columns=myTable.field_names)
plt.table(cellText=df.values, colLabels=df.columns, loc='center')

plt.show()

enter image description here

Mehdi Khademloo
  • 2,754
  • 2
  • 20
  • 40