Python数据可视化之matplotlib实践--入门部分

306 阅读8分钟

本文为学习笔记,仅供自己复习回顾使用,若有侵权可删除

第一章常用的几个操作

坐标轴展示范围设定

plt.xlim(0.05,10)

plt.xlim(10,1) 
'''
xlim()实现将“使用年限”的刻度标签值降序排列,其中的关键是将函数
xlim(xmin,xmax)的参数 xmin 和 xmax 调换顺序,进而变成 xlim(xmax,xmin)实现的可视化效果
'''

坐标轴标签

plt.xticks(np.arange(0,361,60))\

plt.xticks([-2*np.pi,-3*np.pi/2,-1*np.pi,-1*(np.pi)/2,0,(np.pi)/2,np.pi,3*np.pi/2,2*np.pi],
           [r"$-2\pi$",r"$-3\pi/2$",r"$-\pi$",r"$-\pi/2$",r"$0$",r"$\pi/2$",r"$\pi$",r"$3\pi/2$",r"$2\pi$"])

plt.yticks([15,25],["歌剧院 A","歌剧院 B"])

参考线

plt.axhline(y=0.6,c="r",ls="--",lw=2) #x轴方向 plt.axvline(x=4.0,c="r",ls="--",lw=2) #y轴方向

参考范围

plt.axvspan(xmin=4.0,xmax=6.0,facecolor="y",alpha=0.3) #y轴方向 plt.axhspan(ymin=0.0,ymax=0.5,facecolor="y",alpha=0.3) #x轴参考范围

文字注释

plt.annotate("maximum", xy=(np.pi/2,1.0), xytext=((np.pi/2)+1.0,.8),  
              weight="bold", color="g",
             arrowprops =dict(arrowstyle="->",connectionstyle="arc3",color="b"))
#weight:注释文本的字体粗细风格
#arrowprops:指示被注释内容的箭头的属性字典

plt.text(3.10,0.09,"y=sin(x)",weight="bold",color="b")

去掉边框及刻度线设置

# turn the top spine and the right spine off
for spine in plt.gca().spines.keys():
    if spine == "top" or spine == "right":
        plt.gca().spines[spine].set_color("none")
# turn bottom tick for x-axis on
plt.gca().xaxis.set_ticks_position("bottom")
# set tick_line position of bottom
# leave left ticks for y-axis on
plt.gca().yaxis.set_ticks_position("left")
# set tick_line position of left

第二章和第三章统计图详解

柱状图

plt.bar(x,y,align="center",color="c",tick_label=["q","a","c","e","r","j","b","p"],hatch="/") #hatch:/ \ | - . o O x + #align="edge"

条形图

plt.barh(x,y,align="center",color="c",tick_label=["q","a","c","e","r","j","b","p"],hatch="/") #x是y轴的标签,y是柱体宽度

间断条形图

plt.broken_barh([(30,100),(180,50),(260,70)],(20,8),facecolors="#1f78b4") 
#横坐标30,向前100,即(30130),(20,8)指纵坐标20向上8即(20,28)
plt.broken_barh([(60,90),(190,20),(230,30),(280,60)],(10,8),
                    facecolors=("#7fc97f","#beaed4","#fdc086","#ffff99"))

堆积图

plt.bar(x,y,align="center",color="#66c2a5",tick_label=["A","B","C","D","E"],label="班级 A")
plt.bar(x,y1,align="center",bottom=y,color="#8da0cb",label="班级 B")  #bottom变成了上个y

#横向
plt.barh(x,y,align="center",color="#66c2a5",tick_label=["A","B","C","D","E"],label="班级 A")
plt.barh(x,y1,align="center",left=y,color="#8da0cb",label="班级 B") #left是上个y

分块图

plt.bar(x,y,bar_width,color="c",align="center",label="班级 A",alpha=0.5)
plt.bar(x+bar_width,y1,bar_width,color="b",align="center",label=" 班 级 B",alpha=0.5) #设置柱宽

#横向
plt.barh(x,y,bar_width,color="c",align="center",label="班级 A",alpha=0.5)
plt.barh(x+bar_width,y1,bar_width,color="b",align="center",label="班级 B",alpha=0.5) 

直方图

plt.hist(x,bins=bins,color="g",histtype="bar",rwidth=1,alpha=0.6) #bin 范围左闭右开,最后一个左闭右闭 histtype 直方图类型柱状图

堆积直方图

scoresT1 = np.random.randint(0,100,100)
scoresT2 = np.random.randint(0,100,100)
x = [scoresT1,scoresT2]
colors = ["#8dd3c7","#bebada"]
labels = ["班级 A","班级 B"]
# plot histogram
bins = range(0,101,10)
plt.hist(x,bins=bins,color=colors,histtype="bar",
         rwidth=10,stacked=True,label=labels)  #stacked实现堆积

并排直方图

plt.hist(x,bins=bins,color=colors,histtype="bar",rwidth=10,stacked=False,label=labels)

饼图

plt.pie(soldNums,labels=kinds,autopct="%3.1f%%",startangle=60,colors=colors)

explode = (0.1,0.1,0.1,0.1)
plt.pie(students,explode=explode,labels=labels,autopct="%3.1f%%",startangle=30,shadow=True,colors=colors)
'''
explode:饼片边缘偏离半径的百分比
autopct:饼片文本标签内容对应的数值百分比样式
startangle:从 x 轴作为起始位置,第一个饼片逆时针旋转的角度
shadow:是否绘制饼片的阴影
'''

plt.pie(students,labels=labels,autopct="%3.1f%%",startangle=45,pctdistance=0.5,labeldistance=1.2,colors=colors)
'''
参数 pctdistance和 labeldistance 的具体取值,这两个参数分别控制百分比数值和标签值的显示位置,它们都是以半径
长度比例值作为显示位置依据的
'''

环状饼图

elements = ["面粉","砂糖","奶油","草莓酱","坚果"]
weight1 = [40,15,20,10,15]
weight2 = [30,25,15,20,10]
colormapList = ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00"]
outer_colors = colormapList
inner_colors = colormapList
wedges1,texts1,autotexts1 = plt.pie(weight1,autopct="%3.1f%%",radius=1,pctdistance=0.85,colors=outer_colors,
                                    textprops=dict(color="w"),wedgeprops=dict(width=0.3,edgecolor="w"))
                                    #wedgeprops代表环的宽度
wedges2,texts2,autotexts2 = plt.pie(weight2,autopct="%3.1f%%",radius=0.7,pctdistance=0.75,colors=inner_colors,
                                    textprops=dict(color="w"),wedgeprops=dict(width=0.3,edgecolor="w"))
plt.legend(wedges1,elements,fontsize=12,title="配料表",loc="center left",bbox_to_anchor=(0.91, 0, 0.3, 1))
plt.setp(autotexts1,size=15,weight="bold") #样式设置
plt.setp(autotexts2,size=15,weight="bold")
plt.setp(texts1,size=12)

极线图

barSlices = 12
theta = np.linspace(0.0, 2*np.pi, barSlices, endpoint=False)
r = 30*np.random.rand(barSlices)
plt.pie(soldNums,labels=kinds,autopct="%3.1f%%",startangle=60,colors=colors)

气泡图

plt.scatter(a,b,s=np.power(10*a+20*b,2),c=np.random.rand(100),cmap=mpl.cm.RdYlBu,marker="o")

棉棒图

plt.stem(x,y,linefmt="-.",markerfmt="o",basefmt="-")

箱线图

bplot = plt.boxplot(testList,whis=whis,widths=width,sym="o",labels=labels,patch_artist=True,notch = True)
'''
whis:四分位间距的倍数,用来确定箱须包含数据的范围的大小
        IQR( IQR 是 Inter-Quartile Range 的缩写)是四分位差,计算方法是 IQR=Q3−Q1。
        离群值 Outlier 的判断标准是 value<( Q1−whis×IQR) 或者 value>( Q3+whis×IQR)
widths:设置箱体的宽度。
sym:离群值的标记样式
patch_artist:是否给箱体添加颜色
notch:是否往里凹一点
'''
for patch,color in zip(bplot["boxes"],colors):
    patch.set_facecolor(color)

plt.boxplot(x,showmeans =True, meanline=True, )  #vert水平方向箱线图
'''
meanline:是否用线的形式表示均值,默认用点来表示;
showmeans:是否显示均值,默认不显示;
showcaps:是否显示箱线图顶端和末端的两条线,默认显示;
showbox:是否显示箱线图的箱体,默认显示;
showfliers:是否显示异常值,默认显示;

'''

#横向
plt.boxplot(x,vert=False)  #vert水平方向箱线图

误差棒图

x = np.linspace(0.1,0.6,10)
y = np.exp(x)
error = 0.05+0.15*x
lower_error = error
upper_error = 0.3*error
error_limit = [lower_error,upper_error]
plt.errorbar(x,y,yerr=error_limit,fmt=":o",ecolor="y",elinewidth=4,ms=5,mfc="c",mec='r',capthick=1,capsize=2)
'''
   yerr:单一数值的非对称形式误差范围。
 fmt:数据点的标记样式和数据点标记的连接线样式。
 ecolor:误差棒的线条颜色。
 elinewidth:误差棒的线条粗细。
 ms:数据点的大小。
 mfc:数据点的标记颜色。
 mec:数据点的标记边缘颜色。
 capthick:误差棒边界横杠的厚度。
 capsize:误差棒边界横杠的大小
'''

柱状图上加误差棒图

x = np.arange(5)
y = [100,68,79,91,82]
std_err = [7,2,6,10,5]
error_attri = dict(elinewidth=2,ecolor="black",capsize=3)
# create bar with errorbar
plt.bar(x,y,color="c",width=0.6,align="center",yerr=std_err,error_kw=error_attri,
                        tick_label=["园区 1","园区 2","园区 3","园区 4","园区 5"])

#横向
x = np.arange(5)
y = [1200,2400,1800,2200,1600]
std_err = [150,100,180,130,80]
bar_width = 0.6
colors = ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00"]
# create horizontal bar
plt.barh(x,y,bar_width,color=colors,align="center",xerr=std_err,
                tick_label=["家庭","小说","心理","科技","儿童"])

堆积折线图

plt.stackplot(x,y,y1,y2,labels=labels,colors=colors)

阶梯图

plt.step(x,y,color="#8dd3c7", where="pre",lw=2)
'''
参数值“pre”表示 x 轴上的每个数据点对应的 y 轴上的数值
向左侧绘制水平线直到 x 轴上的此数据点的左侧相邻数据点为止,也就是说, x 轴上的相邻数据点的
取值是按照左开右闭区间进行数据点选取的
“post”表示在 x 轴上的相邻数据点的取值是按照左闭右开区间进行数据点选取的,
然后用对应的 y 轴上的数值向右侧绘制水平线直到 x 轴上的此数据点的右侧相邻数据点为止
'''

第四章完善图形

图例

plt.plot(x,y1,label=r"$\cos(x)$") ''' 对于在“r"text12text1\text2"”中的非数学表达式文本 text1 会以斜体形式输出, 并且最终输出时就会呈现印刷级别的文档效果 ''' plt.legend(loc="upper left",bbox_to_anchor=(0.05,0.95,),ncol=3,title="power function",shadow=True,fancybox=True) ''' 线框位置参数 bbox_to_anchor 一个四元元组, 且使用 Axes 坐标系统。 第 1个元素代表距离画布左侧的 x 轴长度的倍数的距离; 第 2 个元素代表距离画布底部的 y 轴长度的倍数的距离; 第 3 个元素代表 x 轴长度的倍数的线框长度; 第 4 个元素代表 y 轴长度的倍数的线框宽度

线框圆角处理参数 fancybox 位置: upper right 1 upper left 2 lower left 3 lower right 4 center left 6 center right 7 lower center 8 upper center 9 center 10 '''

标题

plt.title("Left Demo",loc="left",fontdict={"size":"xx-large","color":"r","family":"Times New Roman"}) #可放字典里
plt.title("right demo",loc="right",family="Comic Sans MS",size=20,style="oblique",color="c") #也可单独作为参数

饼图图例

elements = ["面粉","砂糖","奶油","草莓酱","坚果"]
weight = [40,15,20,10,15]
colors = ["#1b9e77","#d95f02","#7570b3","#66a61e","#e6ab02"]
wedges, texts, autotexts = plt.pie(weight,autopct="%3.1f%%",textprops=dict(color="w"),colors=colors)
plt.legend(wedges,elements,fontsize=12,title="配料表",loc="center left",bbox_to_anchor=(0.91, 0, 0.3, 1))
'''
通过调用图例函数“plt.legend(wedges,elements)”,我们就可以将饼片外部的文本标签放在图例
中,而饼片的数值标签仍然放在饼片内部。函数 legend()的参数 wedges 和 elements 分别表示饼片实
例列表和文本标签列表,而且这两个参数要一起配合使用才可以将饼片外部的文本标签放置在图例
内部的任务中。
'''
plt.setp(autotexts, size=15, weight="bold")
plt.setp(texts,size=12)

图中加表

# add table to pie figure
colLabels = ["A 难度水平","B 难度水平","C 难度水平","D 难度水平"]
rowLabels = ["学生选择试卷人数"]
studentValues = [[350,150,200,300]]
colColors = ["#377eb8","#e41a1c","#4daf4a","#984ea3"]
plt.table(cellText=studentValues, #表格的数值,将源数据按照行进行分组,每组数据放在列表里存储,所有组数据再放在列表里储存
          cellLoc="center",       #表格中的数据对齐位置,可以左对齐、居中和右对齐
          colWidths=[0.1]*4,      #表格每列的宽度
          colLabels=colLabels,   #表格每列的列名称
          colColours=colColors,  #表格每列的列名称所在单元格的颜色
          rowLabels=rowLabels,  #表格每行的行名称
          rowLoc="center",    #表格每行的行名称对齐位置,可以左对齐、居中和右对齐
          loc="bottom"     #表格在画布中的位置
         )