搞了两个周的前端,再熟悉一下Anaconda吧~~~
还是对于数据的处理,不过重点是最后生成的图片要是透明的……
可视化这一块最烦人的还是坐标问题,总是感觉有bug,参数太多,官方文档说得不够明白,哎……直接上代码吧:
import numpy as np import matplotlib.pyplot as plt from pylab import mpl import scipy.stats as stats # 设置中文字体 mpl.rcParams['font.sans-serif'] = ['SimHei'] def autolabel(rects): # attach some text labels for rect in rects: height = rect.get_height() # 设置标注文字及位置 ax.text(rect.get_x() + rect.get_width() / 2, 0.03 + height, '%.4f' % height, ha='center', va='bottom')#ha和va分贝设置水平和垂直对齐方式 #text(x, y, s, fontdict=None, withdash=False, **kwargs);x, y:表示坐标;s:字符串文本;fontdict:字典,可选; #kw: fontsize=12,horizontalalignment=‘center’或ha=’cener’ ,verticalalignment=’center’或va=’center’ # 数据 testData = [[0.8, 0.4, 0.6], [0.7, 0.6, 0.3], [0.8, 0.5, 0.4] ] N = 3,width = 0.5 ind = np.arange(width, width*4*N, width*4) #参数分别代表起始位,终止位和步长 fig, ax = plt.subplots() #bar(x,height, width,*,align='center',**kwargs),其中x为包含所有柱子的下标的列表 rectsTest1 = ax.bar(ind, (testData[0][0], testData[0][1], testData[0][2]), width, color=(0, 0, 1, 1), edgecolor=(0, 0, 1, 1)) #edgecolor为边框颜色 rectsTest2 = ax.bar(ind + width, (testData[1][0], testData[1][1], testData[1][2]), width, color=(1, 0, 0, 1), edgecolor=(1, 0, 0, 1)) rectsTest3 = ax.bar(ind + 2*width, (testData[2][0], testData[2][1], testData[2][2]), width, color=(0, 1, 0, 1), edgecolor=(0, 1, 0, 1)) ax.set_xlim(0, 6) ax.set_ylim(0, 1.4)#设定y轴取值范围 ax.set_ylabel('数值') #设置y轴标签 ax.yaxis.grid(True) #y轴上生成网格 ax.set_xticks(ind + width) #告诉matplotlib要将刻度放在数据范围中的哪些位置 ax.set_xticklabels(('A', 'B', 'C')) #刻度标签 # 设置图例 legend = ax.legend((rectsTest1, rectsTest2, rectsTest3), ('test1', 'test2', 'test3')) #函数原型 legend(*args, **kwargs),当len(args) == 2,args 是[artist]和[label]的集合;当len(args) == 0,args会自动调用get_legend_handles_labels()生成 #等价于handles, labels = ax.get_legend_handles_labels(),ax.legend(handles, labels) #ax.get_legend_handles_labels()的作用在于返回ax.lines, ax.patch所有对象以及ax.collection中的LineCollection or RegularPolyCollection对象 frame = legend.get_frame() #返回legend所在的方形对象 frame.set_alpha(1) #0~255透明度值 frame.set_facecolor('none') # 设置图例legend背景透明 # 给每个数据矩形标注数值 autolabel(rectsTest1) autolabel(rectsTest2) autolabel(rectsTest3) plt.savefig('D:/照片/test.png', format='png', bbox_inches='tight', transparent=True, dpi=600) # bbox_inches='tight' 图片边界空白紧致, 背景透明
注释已经很详细了,这一块还得经常练,很多属性容易忘。。
效果如下: