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:
How can do it so that the prettytable always remains centered above the plot without distorting the plot.
CodePudding user response:
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()