from matplotlib import patches
采用patches.Rectangle()绘制长方形
获得了长方形对象后,使用对画布添加对象的命令add_artist(),将矩形添加到我们的图像中;
例子:画有序条形图
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline from matplotlib import patches # step1 : 导入数据 df_raw = pd.read_excel("C:\\Users\\30565\\Documents\\Python Scripts\\data-visualization-50\\mpg_ggplot2.xlsx") df_raw.head()
df = df_raw[[‘cty‘,‘manufacturer‘]].groupby("manufacturer").apply(lambda x:x.mean()) df
df.sort_values(‘cty‘,inplace=True) #排序 df.reset_index(inplace=True) #修正索引 # step2: 绘制有序条形图 fig,ax = plt.subplots(figsize=(16,10)) #往后均是对ax坐标系操作 # 绘制柱状图 ax.vlines(x=df.index #横坐标 ,ymin=0 # 柱状图在y轴的起点 ,ymax = df.cty # 柱状图在y轴的终点 ,color = ‘firebrick‘ # 柱状图的颜色 ,alpha = 0.7 # 柱状图的透明度 ,linewidth = 20) # 柱状图的线宽 # step3:添加文本 # enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标, for i, cty, in enumerate(df.cty): ax.text(i, # 文本的横坐标位置 cty+0.5, # 文本的纵坐标位置 round(cty, 1), # 对文本中数据保留一位小数 horizontalalignment = ‘center‘) # 相对于xy轴,水平对齐 # step4:添加补丁 # 添加绿色的补丁 p1 = patches.Rectangle((0.57, -0.005), # 矩形左下角坐标 width = 0.335, # 矩形的宽度 height = 0.13, # 矩形的高度 alpha = 0.1, # 矩阵的透明度 facecolor = ‘green‘ # 是否填充矩阵(设置为绿色) ) # 保持矩形显示在图像最上方 # 添加红色的补丁 p2 = patches.Rectangle((0.124, -0.005), # 矩形左下角坐标 width = 0.446, # 矩形的宽度 height = 0.13, # 矩形的高度 alpha = 0.1, # 矩阵的透明度 facecolor = ‘red‘ # 是否填充矩阵(设置为红色) ) # 保持矩形显示在图像最上方 # 将补丁添加至画布 fig.add_artist(p1) # 获取子图,并且将补丁添加至子图 fig.add_artist(p2) # 获取子图,并且将补丁添加至子图 # step5:装饰 ax.set(ylabel=‘Miles Per Gallon‘,ylim=(0, 30)) # 横坐标的刻度标尺 plt.xticks(df.index, # 横坐标的刻度位置 df.manufacturer.str.upper(), # 刻度标尺的内容(先转化为字符串,再转换为大写) rotation = 60, # 旋转角度 horizontalalignment = ‘right‘, # 相对于刻度标尺右移 fontsize = 12) # 字体尺寸 plt.title(‘Bar Chart for Highway Mileage‘, # 子图标题名称 fontdict = {‘size‘: 22}) # 标题字体尺寸 plt.show() # 显示图像
观察 patches.Rectangle((x,y),width,height)参数
发现其中的x,y和坐标轴中的x,y是不一致的,也就是我们建立的坐标轴是没用的!
我们发现,x,y,width,height均是小于1的数据,通过测试发现,其实整个画布的左下角坐标是(0,0),width=1,height=1
如
patches.Rectangle((x,y),width,height)参数
原文:https://www.cnblogs.com/ivyharding/p/12731205.html