I'm trying to plot a square rectangle from a given dataframe. I've been able to code till the horizontal line, but the square rectangle patch isn't working.
Here is my code for reference
tips = pd.DataFrame([20, 10, 50, 60, 90, 20, 30, 15, 75, 35], columns = ['Tips'])
tips.index += 1
tips.index.name = 'Meals'
next_tip = tips.mean()
tips['Tips'] = tips['Tips'].astype(float)
tips['Residuals'] = tips['Tips'] - float(next_tip)
plot = tips.reset_index().plot.scatter(x=tips.index.name, y='Tips', label='Tip Amount', s=60, figsize=(15,5))
plot.axhline(next_tip[0], linestyle='dashdot', color='orange', linewidth=3, label='Best fit')
plot.annotate(' -20.5', xy=(1, 40.5), xytext=(1, 20), arrowprops=dict(facecolor='black', width=0.1, headwidth=6))
plot.annotate(' 19.5', xy=(4, 40.5), xytext=(4, 60), arrowprops=dict(facecolor='black', width=0.1, headwidth=6))
plot.annotate(' -9.5', xy=(7, 40.5), xytext=(7, 30), arrowprops=dict(facecolor='black', width=0.1, headwidth=6))
plot.patches(xy=(1, 20), width=20, height=20)
In order to add a rectangle to your axes you need to create a rectangle patch using matplotlib.patches.Rectangle
, and then add it to you axes using axes.add_patch
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import pandas as pd
tips = pd.DataFrame([20, 10, 50, 60, 90, 20, 30, 15, 75, 35], columns = ['Tips'])
tips.index += 1
tips.index.name = 'Meals'
next_tip = tips.mean()
tips['Tips'] = tips['Tips'].astype(float)
tips['Residuals'] = tips['Tips'] - float(next_tip)
plot = tips.reset_index().plot.scatter(x=tips.index.name, y='Tips', label='Tip Amount', s=60, figsize=(15,5))
plot.axhline(next_tip[0], linestyle='dashdot', color='orange', linewidth=3, label='Best fit')
plot.annotate(' -20.5', xy=(1, 40.5), xytext=(1, 20), arrowprops=dict(facecolor='black', width=0.1, headwidth=6))
plot.annotate(' 19.5', xy=(4, 40.5), xytext=(4, 60), arrowprops=dict(facecolor='black', width=0.1, headwidth=6))
plot.annotate(' -9.5', xy=(7, 40.5), xytext=(7, 30), arrowprops=dict(facecolor='black', width=0.1, headwidth=6))
# create the rectangle
rect = patches.Rectangle(xy=(1, 20), width=20, height=20, fill=False)
# add it to the axes
plot.add_patch(rect)
plt.show()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.