![](/img/trans.png)
[英]Avoid slow looping when plotting irregular raster plot using patches.Rectangle
[英]Plot rectangle patches using pandas with horizontal line
我正在嘗試從給定的數據框中繪制一個正方形矩形。 我一直可以編碼直到水平線,但方形矩形補丁無法正常工作。
這是我的代碼供參考
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)
為了在軸上添加矩形,您需要使用matplotlib.patches.Rectangle
創建一個矩形面片,然后使用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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.