matplob对图片处理实践(1)

  1. tableau20 = [(31119180), (174199232), (25512714), (255187120),    
  2.              (4416044), (152223138), (2143940), (255152150),    
  3.              (148103189), (197176213), (1408675), (196156148),    
  4.              (227119194), (247182210), (127127127), (199199199),    
  5.              (18818934), (219219141), (23190207), (158218229)]    
  6.   
  7. # Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts.    
  8. for i in range(len(tableau20)):    
  9.     r, g, b = tableau20[i]    
  10.     tableau20[i] = (r / 255., g / 255., b / 255.)    
  11.   
  12. #设置图的大小  
  13. plt.figure(figsize=(1214))  
  14. #限制坐标轴的范围,防止出现大片空白  
  15. plt.ylim(090)      
  16. plt.xlim(19682014)   
  17. #x,y上的数据名称  
  18. plt.xlabel("x")  
  19. plt.ylabel("y")  
  20. #去掉上下左右的黑色框线  
  21. ax = plt.subplot(111)      
  22. ax.spines["top"].set_visible(False)      
  23. ax.spines["bottom"].set_visible(False)      
  24. ax.spines["right"].set_visible(False)      
  25. ax.spines["left"].set_visible(False)   
  26.   
  27. #坐标轴上的数字出现在上还是下,左还是右?  
  28. #ax.get_xaxis().tick_top()  
  29. ax.get_xaxis().tick_bottom()  
  30. #ax.get_yaxis().tick_left()  
  31. ax.get_yaxis().tick_right()  
  32.   
  33. #调整坐标轴上的字体以及格式  
  34. plt.yticks(range(09110), [str(x) + "%" for x in range(09110)], fontsize=14)    #第一个参数是文字位置,第二个参数是文字  
  35. plt.xticks(fontsize=14)    
  36.   
  37. #右上角的图例,元组形式  
  38. plt.legend((rect,),(u<span style="color:#ff00bf;">"图例"</span>,))  
  39.   
  40. #沿着每个坐标绘制虚线,方便查看坐标值  
  41. for y in range(109110):      
  42.     plt.plot(range(19682012), [y] * len(range(19682012)), "--", lw=0.5, color="black", alpha=0.3)    
  43.   
  44.   
  45. #去掉坐标上的数字和小线,top等是去掉tick mark,labelbottom是下边的文字标记  
  46. plt.tick_params(axis="both", which="both", bottom="off", top="off",      
  47.                 labelbottom="on", left="off", right="off", labelleft="on")  


2、曲线

  1. </pre><pre name="code" class="python">  
  2. plt.plot(xilst, ylist, lw=2.5,  color=tableau20[0])  
  3. #在每个线的后面加上描述,其实就是指定位置添加文本  
  4. plt.text(x_pos, y_pos, info, fontsize=14, color=tableau20[rank])  


标题:
  1. plt.text(199593"Percentage of Bachelor's degrees conferred to women in the U.S.A., by major (1970-2012)", fontsize=17, ha="center")  

在图里面包含数据来源以及版权:
  1. plt.text(1966, -8"Data source: nces.ed.gov/programs/digest/2013menu_tables.asp"      
  2.        "\nAuthor: Randy Olson (randalolson.com / @randal_olson)"      
  3.        "\nNote: Some majors are missing because the historical data "      
  4.        "is not available for them", fontsize=10)   

保存成png格式或其他:
  1. #bbox_inches="tight"表示去除边缘部分的空白  
  2. plt.savefig("percent-bachelors-degrees-women-usa.png", bbox_inches="tight")   




3、直方图

  1. data = list(np.random.randn(10000))  
  2. data1 = list(2*np.random.randn(10000))  
  3.   
  4.   
  5. info = r'$\mu=0.1, \ \sigma= %f$' % (0.2)   
  6.   
  7. plt.text(10.1, info, bbox=dict(facecolor='red', alpha=0.25))#前两个值表示文本框放置的位置  
  8. plt.hist(data, 50, normed=True, facecolor='r', alpha=1)#50表示把数据的区间分成多少份进行统计, normed指求得是频数还是频率,alpha都表示透明程度,越小越透明</span>  
  9. plt.hist(data1, 100, normed=True, facecolor='g', alpha=0.8)  
  10. plt.grid(True)  
  11. plt.show()  

现在plot.ly提供了交互的动态图,只需要添加一行代码即可。


4、实践一:绘制confusion matrix

  1. import matplotlib.pyplot as plt  
  2. from sklearn.metrics import confusion_matrix  
  3. import numpy as np  
  4.   
  5. def makeconf(conf_arr, model_name):  
  6.     # makes a confusion matrix plot when provided a matrix conf_arr  
  7.     # every row of conf_arr is normalized  
  8.     norm_conf = []  
  9.     for i in conf_arr:  
  10.         a = 0  
  11.         tmp_arr = []  
  12.         a = sum(i, 0)  
  13.         for j in i:  
  14.             tmp_arr.append(float(j)/float(a))  
  15.         norm_conf.append(tmp_arr)  
  16.   
  17.     fig = plt.figure()  
  18.     plt.clf() #清除画布  
  19.     ax = fig.add_subplot(111#参数的意思是把画布分成1行1列,把图画在第1块(从上到下从左到右数起)。也可以写成 fig.add_subplot(1,1,1)  
  20.     ax.set_aspect(1#控制纵横比,1:1  
  21.     res = ax.imshow(np.array(norm_conf), cmap=plt.cm.jet,   
  22.                     interpolation='nearest'#根据np array的数组绘制图,第二个参数是配色,有jet、gray  
  23.   
  24.     width = len(conf_arr)  
  25.     height = len(conf_arr[0])  
  26.   
  27.     for x in xrange(width):  
  28.         for y in xrange(height):  
  29.             ax.annotate(str(conf_arr[x][y]), xy=(y, x),   
  30.                         horizontalalignment='center',  
  31.                         verticalalignment='center') #在每一块表上数字,第一个参数是要标上的字符串,第二个是坐标  
  32.   
  33.     cb = fig.colorbar(res)  #在图的旁边绘制一个bar,展示颜色代表的数值  
  34.     indexs = '0123456789'  
  35.     plt.xticks(range(width), indexs[:width]) #x, y轴的坐标名  
  36.     plt.yticks(range(height), indexs[:height])  
  37.     # you can save the figure here with:  
  38.     # plt.savefig("pathname/image.png")  
  39.     plt.savefig("conf_matrix/{}_confusion_matrix.png".format(model_name))  
  40.       
  41. if __name__=="__main__":  
  42.     y = [1,0,1,1,1,0,0]  
  43.     predicts = [1,1,0,1,0,1,0]  
  44.     conf_matrix = confusion_matrix(y, predicts)  
  45.     print conf_matrix  
  46.     makeconf(conf_matrix, "test")     
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值