import matplotlib as mpl
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator
from matplotlib.ticker import MultipleLocator
from matplotlib.ticker import FuncFormatter
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import pandas as pd
import scipy
import seaborn as sns
from sklearn.datasets import make_blobs
class changeFunc():
def change_xyname(self):
plt.xlabel("# BoxNumber")
plt.ylabel("BoxWeight"
,labelpad=10 #设置与坐标轴之间的距离
)
def change_legend(self):
legend = plt.legend(loc="upper left"
#bbox_to_anchor与图例的位置有关, 可以自定义图例位置, 坐标表示的数值是比例但与loc冲突
#原点在左下角, (0,0)左下角; (1,0)右下角; (0.5,0.5)中间;
#, bbox_to_anchor=(0.5, 1.05)
, ncol=3 # 图例的列的数量,默认为1
, fontsize=8
#,prop = {'size':8} #调整图例大小, 与设置fontsize=8是相同的效果
#, borderpad=50 #调整图例大小
, handlelength=1 # 图例句柄的长度
, handleheight=2 #句柄的高度
, handletextpad=0.5 #句柄和标签之间的间距
, columnspacing = 0.9 #调整不同列之间的间距
, frameon=True # 是否显示图例边框
, edgecolor='black' #边框颜色为黑色
, framealpha=1 # 控制图例框的透明度
# , borderpad=0.3 # 图例框内边距
# , markerfirst=True # True表示图例标签在句柄右侧,false反之
# , title="power function" # 为图例添加标题
# , shadow=True # 是否为图例边框添加阴影
# , fancybox=True # 是否将图例框的边角设为圆形
)
#设置图例的不透明度为100%
legend.get_frame().set_alpha(1)
def change_plot(self,x=(0,101,100),y=(0.45,1.0,100),color="orange"):
x = np.random.randint(*x)
x.sort()
y=np.random.uniform(*y)
y.sort()
plt.plot(x
,y
,ls="-"
,lw=2
,color=color
#,marker="o" #在数据点处绘制圆形标记
#,ms=20 #设置圆形标记的大小
#,mfc="c" #设置圆形标记的填充颜色
#,mec="c" #设置圆形标记的边缘颜色为青色
,label="legend")
def change_grid(self):
#绘制网格线
plt.grid(True #是否显示网格线
,axis="y" #只在y轴显示网格线, 可选参数"x", "y", "both"
,ls=":" #网格线的线型为点线, "-"代表实线, 全称为linestyle
,color="r" #color:线条颜色, "gray"代表灰色
,alpha=0.3 #设置不透明度
,lw=1 #网格线的宽度为1
)
def change_title(self):
# 设置标题
plt.title("# Parameter "
, loc="center"
, size=10
, style="oblique"
, y=-0.3
, color="black")
#画各种柱状图
def change_bar(self):
x = np.arange(5)
y = list(np.random.randint(0, 10, 5))
y1 = list(np.random.randint(0, 10, 5))
y2 = list(np.random.randint(0, 10, 5))
bar_width = 0.35
tick_label = ["A", "B", "C", "D", "E"]
plt.bar(x
, y
, bar_width #设置柱子的宽度为).35, 默认值=o.8
, bottom=0 #表示数据的基准高度为0, 即从y=0开始绘制
, align="center"
, color="c"
, tick_label=tick_label
, label="ClassA"
, alpha=0.5
, hatch="///")
#堆积柱状图
plt.bar(x, y1, bar_width,align="center", bottom=y, color="#C9A7BC", label="classB")
#多数据并列柱状图
plt.bar(x + bar_width, y2, bar_width, color="b", align="center", label="ClassB", alpha=0.5)
#画各种条形图
def change_barh(self):
x = np.arange(1,9)
y = list(np.random.randint(0, 10, 8))
y1 = list(np.random.randint(0, 10, 8))
bar_width = 0.35
tick_label = ["A", "B", "C", "D", "E", "F", "G", "H"]
plt.barh(x
, y
, bar_width
, align="center"
, left=0 #left=0表示条形图的左侧基准位置为0, 从x=0开始绘制
, color="c"
, tick_label=tick_label
, hatch="/"
, alpha=0.5
, label="ClassA")
#堆积条形图
plt.barh(x, y1, bar_width, align="center", left=y, color="#FEDD0C", label="ClassB")
#多数据平行条形图
plt.barh(x + bar_width, y1, bar_width, color="b", align="center", label="ClassB", alpha=0.5)
plt.yticks(x + bar_width / 2, tick_label)
#画直方图
def change_hist(self):
# 堆积直方图
x1 = np.random.randint(0, 10, 100)
x2 = np.random.randint(0, 10, 100)
x3=[x1,x2]
colors=["#47D290","#F9C52F"]
labels=["ClassA","ClassB"]
plt.hist(x3
, bins=10 #bins=10代表直方图长条的个数为10
, color=colors
, histtype="bar" #histtype="bar":表示直方图的类型为条形直方图。
# 其他类型包括 'barstacked'(堆叠条形直方图)、'step'(未填充的条形直方图)和 'stepfilled'(填充的条形直方图)
, rwidth=1 #每个柱子的宽度占 bins 宽度的比例。值越大,柱子越宽, 柱子宽度=rwidth×bin宽度; 如果rwidth=1代表比例为100%
, edgecolor="black" #设置直方图的柱子边界为黑色
, stacked=True #stacked=True表示此时为堆叠直方图, 如果不堆叠则stacked=False , label=labels
, label=labels
, orientation="vertical" #指定直方图的方向, vertical表示垂直方向
, alpha=0.6)
#plt.invert_yaxis()是subplot方法
#画饼图
def change_pie(self):
kinds = "easy", "insulation", "luggage", "sealing"
colors = ["#F8D714", "#DF52F6", "#2AACFA", "#E33E30"]
soldNums = [0.05, 0.45, 0.15, 0.35]
explode = (0.1,0.1,0.1,0.1)
plt.pie(soldNums #soldNums代表每个扇区的大小
, labels=kinds #labels=kinds标识每个扇区的名称
, autopct="%3.1f%%" #autopct="%3.1f%%"表示每个扇区的百分比显示格式, %3.1f%表示保留一位小数的百分比
, startangle=60 #startangle=60:表示从x轴作为起始位置, 第一个饼片逆时针旋转的角度
, explode=explode #explode表示饼片边缘偏离半径的百分比
, shadow=True #shadow=True:表示饼图是否有阴影效果
, labeldistance=1.2
, colors=colors)
def change_addTable(self):
col=["A","B","C","D"]
values=[[350,150,200,300]]
label=["StudentNum"]
colColors=["#F8D714","#DF52F6","#2AACFA","#E33E30"]
plt.table(cellText=values #设置表格第二行的值
,cellLoc="center" #设置单元格数据居中对齐
,colWidths=[0.1]*4 #表格每列的宽度
,colLabels=col #设置表格第一行的值
,colColours=colColors #表格列名称单元格的背景色
,rowLabels=label #表格每行的行名称
,rowLoc="center" #表格的行名称对齐位置
,loc="bottom")
#画气泡图或散点图
def change_bubble(self):
a = np.random.randn(100)
b = np.random.randn(100)
plt.scatter(a #散点图x轴
, b #散点图y轴
, s=np.power(10 * a + 20 * b, 2) #设置每个散点大小的变化
, c=np.random.rand(100) #生成100个0到1之间的随机数来设置散点颜色
, cmap=mpl.cm.RdYlBu #指定颜色映射
, marker="o" #指定散点的形状, 这里为圆形("o")
, alpha=0.9
, edgecolors="gray" #散点的边框颜色, 这里设置为灰色
, linewidths=0.5 #图像边框的宽度, 这里设置为0.5
)
class Drawing(changeFunc):
def __init__(self):
# 坐标轴显示范围
self.line_dispaly_range_xmin = 0.05
self.line_dispaly_range_xmax = 10
self.line_x_label_name = "x-axis"
self.line_y_label_name = "y-axis"
#注释
self.line_annotate_string="maximum"
self.sum_operate()
#子图
self.ax1=""
self.ax2=""
self.ax3=""
def sum_operate(self):
#self.draw_pic()
#self.line_operate()
#self.draw_accumuluate_line()
#self.draw_column()
#self.draw_accumuluate_column()
# self.draw_multiple_data_parallel_column()
#self.draw_bar()
# self.draw_accumuluate_bar()
#self.draw_draw_multiple_data_parallel_bar()
#self.draw_break_bar()
#self.draw_histogram()
#self.draw_pie()
#self.draw_polar()
#self.draw_bubble()
#self.draw_stick()
#self.draw_box()
#self.draw_errorBar()
#self.draw_ladder()
#self.draw_3dCurve()
#self.draw_3dScatter()
#self.draw_multiple_uinform_figures()
#self.draw_multiple_uneven_figures()
#self.change_axis_by_subplot()
#self.change_axis_by_mainplot()
#self.change_linspace()
#画图模板
#画两行三列折线图
#self.upper_change_plot()
#self.Draw_Plot_with_2rows_3columns()
# 画一行四列3D散点图
#self.set_3Dxyz_lim_ticks_title()
#self.set_3Dxyz_Value_colorBar_barticks()
self.Draw_3D_Scatter()
plt.show()
def tmp_store(self):
self.draw_pic()
self.line_operate()
self.draw_accumuluate_line()
self.draw_column()
self.draw_accumuluate_column()
self.draw_multiple_data_parallel_column()
self.draw_bar()
self.draw_accumuluate_bar()
self.draw_draw_multiple_data_parallel_bar()
self.draw_break_bar()
self.draw_histogram()
self.draw_pie()
self.draw_polar()
self.draw_bubble()
self.draw_stick()
self.draw_box()
self.draw_errorBar()
self.draw_ladder()
self.draw_3dCurve()
self.draw_3dScatter()
self.draw_multiple_uinform_figures()#设置子图,方法1, 好用
self.draw_multiple_uneven_figures()#设置子图,方法2
self.change_axis_by_subplot()#改变坐标轴, 方法1
self.change_axis_by_mainplot()#改变坐标轴, 方法2, 好用
self.change_linspace()
# 画图模板
# 画两行三列折线图
self.upper_change_plot()
self.Draw_Plot_with_2rows_3columns()
#画一行四列3D散点图
self.set_3Dxyz_lim_ticks_title()
self.set_3Dxyz_Value_colorBar_barticks()
self.Draw_3D_Scatter()
plt.show()
#添加注释
def draw_pic(self):
pass
def line_draw_annotate(self):
#带箭头注释
# 指向被注释内容的箭头属性
arrowprops = dict(arrowstyle="->", connectionstyle="arc3", color="b")
# 添加箭头注释 xy:要注释的位置坐标 xytext:注释文本的位置坐标
plt.annotate(self.line_annotate_string, xy=(np.pi / 2, 1.0), xytext=((np.pi / 2) + 0.15, 1.5), weight="bold",
color="b", arrowprops=arrowprops)
#不带箭头注释
#3.10, 0.90代表在坐标轴中的坐标, 与坐标轴的刻度有关, 如果设置的值在刻度之外则也显示在刻度之外即在图像中不显示
plt.text(3.10,0.09,"y=sin(x)",weight="bold",color="b")
#x轴的各种操作
def line_x_operate(self):
# 设置x轴显示范围: xmin:x轴最小值 xmax:x轴最大值
plt.xlim(self.line_dispaly_range_xmin, self.line_dispaly_range_xmax)
# 垂直于xy轴的参考区域 xmin起始位置 xmax终止位置 facecolor填充颜色 alpha透明度
plt.axvspan(xmin=1.0, xmax=2.0, facecolor="y", alpha=0.3)
# 设置x,y轴标签文本
plt.xlabel(self.line_x_label_name)
# 绘制平行于x轴和y轴的水平参考线
plt.axhline(y=0.0, c="r", ls="--", lw=2)
#y轴的各种操作
def line_y_operate(self):
# 垂直于xy轴的参考区域 xmin起始位置 xmax终止位置 facecolor填充颜色 alpha透明度
plt.axhspan(ymin=1.0, ymax=2.0, facecolor="y", alpha=0.3)
# 设置x,y轴标签文本
plt.ylabel(self.line_y_label_name)
# 绘制平行于x轴和y轴的水平参考线
plt.axvline(x=4.0, c="r", ls="--", lw=2)
#绘制折线图与散点图
def draw_line(self):
# 生成一个等间距的数值序列, 0.5起始值, 3.5结束值, 100序列中包含的数值个数
x=np.linspace(0.5,10,100)
y=np.sin(x)
y1=np.cos(x)
# 生成100个服从正态分页的随机数
y2=np.random.randn(100)
# 设置直线图: x:x轴 y:y轴 ls:线条样式 lw:线条宽度 label:标签文本
plt.plot(x,y,ls="-",lw=2,label="plot figure")
plt.plot(x,y1,ls="-",lw=2,label="plot figure")
# 设置散点图: x:x轴 y:y轴 c:label与散点颜色
plt.scatter(x,y2,c="r",label="scatter figure")
super().change_grid()
super().change_title()
#画堆积折线图
def draw_accumuluate_line(self):
x=np.arange(1,6,1)
y=[0,4,3,5,6]
y1=[1,5,4,2,7]
y2=[3,6,1,6,5]
labels = ["BluePlanet", "BrownPlanet", "GreenPlanet"]
colors = ["#8da0cb", "#fc8d62", "#66c2a5"]
plt.stackplot(x,y,y1,y2,labels=labels,colors=colors)
super().change_legend()
#画柱状图
def draw_column(self):
x=[1,2,3,4,5]
y=[5,8,9,7,2]
tick_label = ["A", "B", "C", "D", "E"]
super().change_bar()
super().change_xyname()
super().change_grid()
super().change_legend()
#画堆积柱状图
def draw_accumuluate_column(self):
x=[1,2,3,4,5]
y=[6,10,4,5,1]
y1=[2,6,3,8,5]
plt.bar(x,y,align="center",color="#EBC702",tick_label=["A","B","C","D","E"],label="classA")
plt.bar(x,y1,align="center",bottom=y,color="#C9A7BC",label="classB")
super().change_xyname()
super().change_legend()
#画多数据并列柱状图
def draw_multiple_data_parallel_column(self):
x=np.arange(5)
y=[6,10,4,5,1]
y1=[2,6,3,8,5]
bar_width=0.35
tick_label=["A","B","C","D","E"]
plt.bar(x,y,bar_width,color="c",align="center",label="ClassA",alpha=0.5)
plt.bar(x+bar_width,y1,bar_width,color="b",align="center",label="ClassB",alpha=0.5)
super().change_xyname()
#在对应的刻度上显示标签
plt.xticks(x+bar_width/2,tick_label)
super().change_legend()
#将np.linspace生成的浮点数转化为字符串形式, 因为浮点数形式在坐标轴上显示有乱码
def change_linspace(self,*arr_a):
ticks = np.linspace(*arr_a)
#f'{tick:.1f}': 格式化tick为保留一位浮点数的浮点数格式字符串, f' ': 格式化字符串, tick:.1f: 保留一位小数的浮点数
label_a = [f'{tick:.1f}' for tick in ticks]
return label_a
#在一个子图上批量画多个不同颜色的折线图
def upper_change_plot(self, y=(0.45,1.0,100)):
color_sum = ["red","green","orange"]
for color_single in color_sum:
super().change_plot(y=y,color=color_single)
def Draw_Plot_with_2rows_3columns(self):
fig, ax = plt.subplots(2
, 3 # 创建2行2行的子图网格
, figsize=(15,5) # 定义画布的大小比例,15:5比较好用
# , gridspec_kw={
#调整的是子图整体之间的边界, 并不能调整子图之间的间距
#'left': 0.1 # 设置子图的左边界, 要保证left<right; bottom<top否则会报错, 说明是从左下角开始设置的
# , 'right': 0.9 # 设置子图的右边界
#,'bottom': 0.1 # 设置子图的下边界
# , 'top': 0.9 # 设置子图的上边界
# , 'wspace': 0.4 # 设置子图间的水平间距与子图平均宽度的比值
# , 'hspace': 0.4 # 设置子图间的垂直间距与子图平均高度的比值
# }
)
# 激活第一个子图并绘制数据
plt.sca(ax[0, 0])
self.change_axis_by_mainplot(xlim=(0,100),ylim=(0.4,1.0),xticks=np.arange(0,101,20),yticks=self.change_linspace(0.4,1.0,7))
self.upper_change_plot()
plt.sca(ax[0, 1])
self.change_axis_by_mainplot(xlim=(0,100),ylim=(0.4,1.0),xticks=np.arange(0,101,20),yticks=self.change_linspace(0.4,1.0,7))
self.upper_change_plot()
plt.sca(ax[0, 2])
self.change_axis_by_mainplot(xlim=(0,100),ylim=(0.4,1.0),xticks=np.arange(0,101,20),yticks=self.change_linspace(0.4,1.0,7))
self.upper_change_plot()
plt.sca(ax[1, 0])
self.change_axis_by_mainplot(xlim=(0,100),ylim=(0.4,1.0),xticks=np.arange(0,101,20),yticks=self.change_linspace(0.2,1.0,5))
self.upper_change_plot(y=(0.3,1.0,100))
plt.sca(ax[1, 1])
self.change_axis_by_mainplot(xlim=(0,100),ylim=(0.4,1.0),xticks=np.arange(0,101,20),yticks=self.change_linspace(0.2,1.0,5))
self.upper_change_plot(y=(0.3, 1.0, 100))
plt.sca(ax[1, 2])
self.change_axis_by_mainplot(xlim=(0,100),ylim=(0.4,1.0),xticks=np.arange(0,101,20),yticks=self.change_linspace(0.2,1.0,5))
self.upper_change_plot(y=(0.3, 1.0, 100))
for i in range(2):
for j in range(3):
plt.sca(ax[i, j])
super().change_legend()
super().change_xyname()
if i==0 and any(j == k for k in range(3)):
# 不带箭头注释
# 3.10, 0.90代表在坐标轴中的坐标, 与坐标轴的刻度有关, 如果设置的值在刻度之外则也显示在刻度之外即在图像中不显示
plt.text(70, 0.5, str((i,j))+" number", color="black")
else:
plt.text(70, 0.3, str((i, j)) + " number", color="black")
fig.tight_layout(h_pad=0.2)
#画3D散点图的辅助函数1
def set_3Dxyz_lim_ticks_title(self, ax,xlim=(0,25),ylim=(0,25),zlim=(0.9935,1.000)
,xticks=np.arange(0,21,5),yticks=np.arange(0,21,5)
,zticks=np.linspace(0.994,1.000,7),graph_title="Sample"):
ax.set_xlim(xlim[0],xlim[1])
ax.set_ylim(ylim[0],ylim[1])
ax.set_zlim3d(zlim[0],zlim[1])
ax.set_xticks(xticks)
ax.set_yticks(yticks)
ax.zaxis.set_ticks(zticks)
# 设置刻度size
ax.tick_params(axis='x', labelsize=8)
ax.tick_params(axis='y', labelsize=8)
ax.tick_params(axis='z', labelsize=8)
ax.set_xlabel('Xlable'
, fontsize=9)
ax.set_ylabel('Ylable'
, fontsize=9)
# ax.set_zlabel('Zlabel')
ax.set_title(graph_title, x=0.5, y=-0.2)
def set_3Dxyz_Value_colorBar_barticks(self,ax,cbar_min_max=(0.9938,1.000),z = np.random.uniform(0.994, 1.000, 100)
,cbar_width="7%",distance_from_image=0.65
,barticks=[0.994, 0.995, 0.996, 0.997, 0.998, 0.999]):
# 绘制3D散点图,颜色由标准化后的 z 值决定
x = np.random.randint(20, size=(100))
y = np.random.randint(20, size=(100))
z = z
cmap = mpl.cm.cool
# norm定义了颜色条的最小值和最大值
norm = mpl.colors.Normalize(vmin=cbar_min_max[0], vmax=cbar_min_max[1])
sc = ax.scatter(x, y, z,
c=z # c代表各散点的颜色由x轴的值在颜色条中取对照决定, 决定了散点的颜色
, cmap=cmap # 决定颜色条的颜色映射由蓝到紫
, norm=norm # 定义颜色条的取值范围
)
# 调整颜色条的长宽高位置参数
axins = inset_axes(ax, width=cbar_width, height="100%", loc='center',
bbox_to_anchor=(distance_from_image # 与图像的间距
, 0., 1, 1), # 不清楚作用
bbox_transform=ax.transAxes, borderpad=0)
cbar = plt.colorbar(sc
, cax=axins # cax=fig.add_subplot(gs[1])
, ax=ax # 画颜色条在图像旁边
)
cbar.set_ticks(barticks)
cbar.ax.tick_params(labelsize=8)
cbar.set_label('Value'
, fontsize=9)
def Draw_3D_Scatter(self):
fig = plt.figure()
gs = plt.GridSpec(1, 4
#, width_ratios=[1, 1,1,1]
, wspace=0.45)#调整子图之间的宽度
#ax1 = fig.add_subplot(121, projection='3d')
ax1 = fig.add_subplot(gs[0,0], projection='3d')
ax2 = fig.add_subplot(gs[0,1], projection='3d')
ax3 = fig.add_subplot(gs[0,2], projection='3d')
ax4 = fig.add_subplot(gs[0,3], projection='3d')
self.set_3Dxyz_lim_ticks_title(ax=ax1)
self.set_3Dxyz_lim_ticks_title(ax=ax2,zlim=(0.9895,1.000),zticks=np.linspace(0.990,1.000,6),graph_title="Sample2")
self.set_3Dxyz_lim_ticks_title(ax=ax3,zlim=(0.9800,0.9975),zticks=np.linspace(0.9800,0.9975,8),graph_title="Sample3")
self.set_3Dxyz_lim_ticks_title(ax=ax4,zlim=(0.988,1.000),zticks=np.linspace(0.990,1.000,6),graph_title="Sample4")
self.set_3Dxyz_Value_colorBar_barticks(ax=ax1)
self.set_3Dxyz_Value_colorBar_barticks(ax=ax2,cbar_min_max=(0.9895,1.000),z=np.random.uniform(0.990,1.000,100),barticks=np.linspace(0.990,0.998,5))
self.set_3Dxyz_Value_colorBar_barticks(ax=ax3,cbar_min_max=(0.9800,1.000),z=np.random.uniform(0.9800,0.9975,100),barticks=np.linspace(0.9825,0.9975,7))
self.set_3Dxyz_Value_colorBar_barticks(ax=ax4,cbar_min_max=(0.988,1.000),z=np.random.uniform(0.990,1.000,100),barticks=np.linspace(0.990,0.998,5))
#fig.tight_layout(h_pad=0.2)
#画条形图
def draw_bar(self):
x = [1, 2, 3, 4, 5, 6, 7, 8]
y = [3, 1, 4, 5, 8, 9, 7, 2]
super().change_barh()
super().change_xyname()
super().change_addTable()
#画堆积条形图
def draw_accumuluate_bar(self):
x=[1,2,3,4,5]
y=[6,10,4,5,1]
y1=[2,5,3,8,5]
plt.barh(x,y,align="center",color="#708B87",tick_label=["A","B","C","D","E"],label="ClassA")
plt.barh(x,y1,align="center",left=y,color="#FEDD0C",label="ClassB")
super().change_xyname()
super().change_legend()
#画多数据平行条形图
def draw_draw_multiple_data_parallel_bar(self):
x=np.arange(5)
y=[6,10,4,5,1]
y1=[2,6,3,8,5]
bar_width=0.35
tick_label = ["A", "B", "C", "D", "E"]
plt.barh(x,y,bar_width,color="c",align="center",label="ClassA",alpha=0.5)
plt.barh(x+bar_width,y1,bar_width,color="b",align="center",label="ClassB",alpha=0.5)
plt.yticks(x+bar_width/2,tick_label)
super().change_xyname()
super().change_legend()
#画间断条形图
def draw_break_bar(self):
plt.broken_barh([(30, 100), (180, 50), (260, 70)], (20, 8), facecolors="#1f78b4")
plt.broken_barh([(60, 90), (190, 20), (230, 30), (280, 60)], (10, 8),
facecolors=("#7fc97f", "#beaed4", "#fdc086", "#ffff99"))
plt.xlim(0, 360)
plt.ylim(5, 35)
plt.xticks(np.arange(0, 361, 60))
plt.yticks([15, 25], ["OperaA", "OperaB"])
super().change_xyname()
super().change_grid()
super().change_title()
#画直方图, 直方图数据中只需要一个参数x, 之后程序统计x中各个数据出现的频率
def draw_histogram(self):
#生成100个范围在(0,10)的数
x=np.random.randint(0,10,100)
y=range(0,11,1)
super().change_hist()
super().change_legend()
super().change_xyname()
#画饼图
def draw_pie(self):
kinds="easy","insulation","luggage","sealing"
colors=["#F8D714","#DF52F6","#2AACFA","#E33E30"]
soldNums=[0.05,0.45,0.15,0.35]
super().change_pie()
super().change_title()
#画极线图
def draw_polar(self):
barSlices=12
theta=np.linspace(0.0,2*np.pi,barSlices,endpoint=False)
r=30*np.random.rand(barSlices)
plt.polar(theta,r,color="chartreuse",linewidth=2,marker="*",mfc="b",ms=10)
#画气泡图
def draw_bubble(self):
super().change_bubble()
#画棉棒图
def draw_stick(self):
x=np.linspace(0.5,2*np.pi,20)
y=np.random.randn(20)
plt.stem(x,y,linefmt="-.",markerfmt="o",basefmt="-")
#画箱线图
def draw_box(self):
x=np.random.randn(1000)
plt.boxplot(x)
plt.xticks([1],["randomMachineAlpha"])
super().change_xyname()
super().change_title()
super().change_grid()
#画误差线图
def draw_errorBar(self):
x=np.linspace(0.1,0.6,6)
y=np.exp(x)
plt.errorbar(x,y,fmt="bo:",yerr=0.2,xerr=0.02)
plt.xlim(0,0.7)
#画阶梯图
def draw_ladder(self):
x = np.linspace(1, 10, 10)
y = np.sin(x)
plt.step(x, y, color="#8dd3c7", where="pre", lw=2)
plt.xlim(0, 11)
plt.xticks(np.arange(1, 11, 1))
plt.ylim(-1.2, 1.2)
#设置刻度线
def change_axis_by_subplot(self):
# self.ax1.set_xlim(0, 4)
# self.ax1.set_ylim(0, 2)
#新建一个图形窗口
fig = plt.figure(figsize=(8,8)
,facecolor="#FFFAE3" #设置图形的背景颜色
)
self.ax1=fig.add_subplot(111)
# #新建一个刻度窗口
# fig.add_axes([0.1 #left:窗口距离图形窗口左边缘的距离为图形窗口宽度的10%
# ,0.4 #bottom:窗口距离图形窗口底部边缘的距离为图形窗口宽度的40%
# ,0.5 #width:窗口的宽度为图形窗口的50%
# ,0.5 #hegith:窗口的高度为图形窗口的50%
# ])
#设置主刻度线的间隔以1.o为单位
self.ax1.xaxis.set_major_locator(MultipleLocator(1.0))
self.ax1.yaxis.set_major_locator(MultipleLocator(1.0))
#设置次要刻度线间隔为1.0/4
self.ax1.xaxis.set_minor_locator(AutoMinorLocator(4))
self.ax1.yaxis.set_minor_locator(AutoMinorLocator(4))
#设置刻度线的外观
self.ax1.tick_params(axis='both' # 作用于x轴还是y轴还是both
, which='major' # 作用于主刻度线还是次要刻度线, major, minor, both
, direction='in' # 刻度在轴域放置的位置: in(里面);out(外面);inout(里面+外面)
, pad=6 # 刻度与对应标签的距离
, length=20
, labelcolor="black" # 刻度标签字体的颜色
, labelrotation=+32 # 刻度标签的旋转,取值为浮点数,正值逆时针旋转;负值顺时针旋转
, width=3
, labelsize=12 # 显示刻度字体大小, 可使用labelsize={'x': 12, 'y': 14}将刻度字体设置为不同值
# , top=True #bottom, top, left, right 布尔值,是否绘制主刻度线,默认绘制left和bottom的
, bottom=False
, left=False
, color='black')
self.ax1.tick_params(
which="minor" #应用于次度刻度线
, length=5 #次度刻度线的长度
, width=1.0 #次度刻度线的宽度
, labelsize=10 #次度刻度线的字体大小
, labelcolor="0.25" #次度刻度线的字体颜色为灰色
, colors="r") #次度刻度线的刻度颜色为红色
def change_axis_by_mainplot(self, xticks=np.arange(123,456,5),yticks=np.arange(123,456,5), xlim=(123,456), ylim=(123,456),zlim=(123,456)):
#当不输入xlim和xlim的值时默认将其值的设置交给matplotlib处理
if xlim != (123,456):
plt.xlim(xlim) # 闭区间
if ylim != (123,456):
plt.ylim(ylim) # 闭区间
if zlim != (123,456):
plt.zlim(zlim) # 闭区间
#设置x和y在固定的刻度显示字符, 如果使用plt.xticks([],[])代表清空刻度
if not np.array_equal(xticks,np.arange(123,456,5)):
plt.xticks(ticks=xticks, labels=xticks)
if not np.array_equal(yticks,np.arange(123,456,5)):
if type(yticks[0])==str:
num_list = list(map(float,yticks))
plt.yticks(ticks=num_list, labels=yticks)
else:
plt.yticks(ticks=yticks, labels=yticks)
# plt.minorticks_on() # 显示次要刻度线
# 设置x轴次要刻度线的间隔为0.5, y轴次要刻度线的间隔为0.1
# plt.gca().xaxis.set_minor_locator(MultipleLocator(0.25))
# plt.gca().yaxis.set_minor_locator(MultipleLocator(0.005))
plt.tick_params(axis='x' # 作用于x轴还是y轴还是both
, which='major' # 作用于主刻度线还是次要刻度线, major, minor, both
, direction='in' # 刻度在轴域放置的位置: in(里面);out(外面);inout(里面+外面)
, pad=6 # 刻度与对应标签的距离
, length=5
, labelcolor="black" # 刻度标签字体的颜色
, labelrotation=0 # 刻度标签的旋转,取值为浮点数,正值逆时针旋转;负值顺时针旋转
, width=3
, labelsize=8 # 显示刻度字体大小, 可使用labelsize={'x': 12, 'y': 14}将刻度字体设置为不同值
# , top=True #bottom, top, left, right 布尔值,是否绘制主刻度线,默认绘制left和bottom的
, bottom=False
, left=False
, color='black')
plt.tick_params(axis='y' # 作用于x轴还是y轴还是both
, which='major' # 作用于主刻度线还是次要刻度线, major, minor, both
, direction='in' # 刻度在轴域放置的位置: in(里面);out(外面);inout(里面+外面)
, pad=6 # 刻度与对应标签的距离
, length=5
, labelcolor="black" # 刻度标签字体的颜色
# , labelrotation=+32 # 刻度标签的旋转,取值为浮点数,正值逆时针旋转;负值顺时针旋转
, width=1
, labelsize=8 # 显示刻度字体大小, 可使用labelsize={'x': 12, 'y': 14}将刻度字体设置为不同值
# , top=True #bottom, top, left, right 布尔值,是否绘制主刻度线,默认绘制left和bottom的
, bottom=False
, left=False
, color='black')
plt.tick_params(axis='both'
, which='minor'
, direction='in'
, length=2.5
, width=0.8
, bottom=False
, left=False
, color='black')
def draw_multiple_uinform_figures(self):
### 手动添加子图
#fig = plt.figure(figsize=(8, 6))
#ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # 指定子图的位置和大小
###
x = np.arange(0,10,0.1)
y = np.sin(x)
fig, ax = plt.subplots(2
,2 #创建2行2行的子图网格
,figsize=(8,4) #定义画布的大小比例
,gridspec_kw={'left':0.1 #设置子图的左边界, 要保证left<right; bottom<top否则会报错, 说明是从左下角开始设置的
, 'right':0.9 #设置子图的右边界
, 'bottom':0.1 #设置子图的下边界
, 'top': 0.9 #设置子图的上边界
, 'wspace':0.4 #设置子图间的水平间距与子图平均宽度的比值
, 'hspace':0.4} #设置子图间的垂直间距与子图平均高度的比值
)
# 激活第一个子图并绘制数据
plt.sca(ax[0, 0])
plt.plot([1,2,3], [4,5,6])
#批量改变子图的xy轴标题和图例
for i in range(2):
for j in range(3):
plt.sca(ax[i, j])
super().change_legend()
super().change_xyname()
if i == 0 and any(j == k for k in range(3)):
# 不带箭头注释
# 3.10, 0.90代表在坐标轴中的坐标, 与坐标轴的刻度有关, 如果设置的值在刻度之外则也显示在刻度之外即在图像中不显示
plt.text(70, 0.5, str((i, j)) + " number", color="black")
else:
plt.text(70, 0.3, str((i, j)) + " number", color="black")
#调整子图之间的间距
fig.tight_layout(h_pad=0.2)
#无法自定义子图的尺寸比例, 但可以在2行3列的子图中第一行3列只画一个图
def draw_multiple_uneven_figures(self):
plt.subplot2grid(
(2,3) #定义网格的大小, 即2行3列
,(0,0) #指定子图的位置, 在第0行第0列
,colspan=2 #指定子图跨越2列
)
x=np.linspace(0.0,4.0,100)
y=np.random.randn(100)
plt.scatter(x,y,c="c")
super().change_title()
plt.subplot2grid((2, 3), (0, 2))
super().change_title()
plt.subplot2grid((2, 3), (1, 0), colspan=3)
x = np.linspace(0.0, 4.0, 100)
y1 = np.sin(x)
plt.plot(x, y1, lw=2, ls="-")
plt.xlim(0, 3)
plt.grid(True, ls=":", c="r")
super().change_title()
plt.suptitle("HeyBro",fontsize=25)
super().change_xyname()
#画3D曲线图
def draw_3dCurve(self):
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1, projection="3d")
x = np.linspace(-10, 10, 100)
y = np.linspace(-10, 10, 100)
z = x ** 10 + y ** 3
ax1.plot(x, y, z, label="3d curve") # 其余参数同2d图
#画3D散点图
def draw_3dScatter(self):
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1, projection="3d")
plt.xlim(0,100)
#生成100 个 3 维数据点,随机分为n组, cluster_std表示分散程度
data = make_blobs(n_samples=100, n_features=2, cluster_std=2
,center_box=(0,20)) #设置数据的取值范围
data2=np.random.uniform(0.994, 1.000, 100)
x = data[0][:, 0]
y = data[0][:, 1]
z = data2
label = data[1]
colors = ""
for i in range(100):
if label[i] == 0:
colors += "r"
elif label[i] == 1:
colors += "g"
else:
colors += "b"
sc=ax1.scatter(x, y, z, zdir="z", c=list(colors)) # zdir为指定z轴方向,其余参数同2d绘图
#创建颜色条
colorbar = fig.colorbar(sc
, ax=ax1
, shrink=0.5 #shrink<1缩短颜色条,>1延长颜色条
, aspect=5) #控制颜色条的宽度
colorbar.set_label('Color Scale')
#设置颜色条刻度
colorbar.set_ticks([0, 0.25, 0.5, 0.75, 1])
ax1.set_xlabel("x")
ax1.set_xlabel("y")
ax1.set_xlabel("z")
def line_operate(self):
self.line_x_operate()
self.line_y_operate()
self.line_draw_annotate()
self.draw_line()
if __name__=="__main__":
draw_a=Drawing()
MatplotLib画图
最新推荐文章于 2025-03-19 21:55:12 发布
467

被折叠的 条评论
为什么被折叠?



