1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Python matplotlib模块实现数据可视化

Python matplotlib模块实现数据可视化

时间:2022-04-16 05:16:08

相关推荐

Python matplotlib模块实现数据可视化

Python matplotlib模块实现数据可视化

代码如下:

# -*- coding: utf-8 -*-import matplotlib.pyplot as pltimport numpy as npfrom random import choice, randintimport pygalplt.style.use('ggplot')#使用ggplot的风格fig = plt.figure()#创建一个基础图#下面这行,设置基础图的标题,fontsize是字体大小,fontweight是字体(吧)fig.suptitle('Suptitle of Figure', fontsize = 14, fontweight = 'bold')fig.set_size_inches(10, 10) #设置基础图大小 #条形图 Bar Figurecustomers = ['Ziggy', 'John', 'Dylan', 'Ringo']customers_index = range(len(customers))print("Customer Index: ", customers)sale_amount = [100, 200, 150, 140]another_sale_amount = [sa + 10 for sa in sale_amount]#下面这行意为:基础图分三行二列,这个条形图使用第一个ax1 = fig.add_subplot(3,2,1)#添加柱状图#ax1.bar(customers_index, sale_amount, width = 0.5, align = 'center', color = 'purple')#参数分别表示:索引/高度/柱状图的透明度/柱状图的宽度/颜色/标签(用于图例)ax1.bar(customers_index, sale_amount, alpha = 0.7, width = 0.5, color = 'purple', label = 'First')ax1.bar(customers_index, another_sale_amount, alpha = 0.7, width = 0.5, color = 'orange', label = 'Second')#设置坐标轴位置ax1.xaxis.set_ticks_position('bottom')ax1.yaxis.set_ticks_position('left')#设置坐标轴所表示的含义ax1.set_xlabel('Customers')ax1.set_ylabel('Sale Amount')#设置横坐标标签ax1.set_xticks(customers_index)ax1.set_xticklabels(customers, rotation = 10) #rotation 表示标签的倾斜角#设置这张条形图的标题ax1.set_title('Bar Figure')#创建图例,loc='best'表示图里的位置随柱状图的位置确定最优位置ax1.legend(loc = 'best')#分布直方图 Hist Figureax2 = fig.add_subplot(3,2,2)mu1, mu2, sigma = 100, 130, 15x1 = mu1 + sigma * np.random.randn(10000)print(x1)x2 = mu2 + sigma * np.random.randn(10000)#设置直方图,bins=50表示每个变量的值应该被分成50份n, bins, patches = ax2.hist(x1, bins = 50, normed = False, color = 'purple')print(n, " ", bins, " ", patches)n, bins, patches = ax2.hist(x2, bins = 50, normed = False, color = 'orange', alpha = 0.5)ax2.xaxis.set_ticks_position('bottom')ax2.yaxis.set_ticks_position('left')ax2.set_xlabel('Bins')ax2.set_ylabel('Number of Values in Bin')ax2.set_title('Hist Figure')#折线图plot_data1 = np.random.randn(10).cumsum()plot_data2 = np.random.randn(10).cumsum()plot_data3 = np.random.randn(10).cumsum()plot_data4 = np.random.randn(10).cumsum()ax3 = fig.add_subplot(3,2,3)#添加折现#‘o’表示圆点,‘+’表示加号,‘*’表示星号,‘s’表示方块#‘-’表示实线,‘--’表示虚线,‘-.’表示点线结合的虚线,‘:’表示点虚线ax3.plot(plot_data1, marker = r'o', color = u'blue', linestyle = '-', label = 'Blue Solid')ax3.plot(plot_data2, marker = r'+', color = u'pink', linestyle = '--', label = 'Pink Dashed')ax3.plot(plot_data3, marker = r'*', color = u'orange', linestyle = '-.', label = 'Orange Dash Dot')ax3.plot(plot_data4, marker = r's', color = u'green', linestyle = ':', label = 'Green Dotted')ax3.xaxis.set_ticks_position('bottom')ax3.yaxis.set_ticks_position('left')ax3.set_xlabel('Draw')ax3.set_ylabel('Random Number')ax3.set_title('Line Figure')ax3.legend(loc = 'best')#散点图+回归线x = np.arange(start = 1., stop = 15., step = 1.)y_linear = x + 5. * np.random.randn(14)y_quadratic = x ** 2 + 10. * np.random.randn(14)fn_linear = np.poly1d(np.polyfit(x, y_linear, deg = 1))fn_quadratic = np.poly1d(np.polyfit(x, y_quadratic, deg = 2))ax4 = fig.add_subplot(3,2,4)#‘bo’表示蓝色圆点ax4.plot(x, y_linear, 'bo', x, y_quadratic, 'go',\x, fn_linear(x), 'b-', x, fn_quadratic(x), 'g-', linewidth = 2.)ax4.xaxis.set_ticks_position('bottom')ax4.yaxis.set_ticks_position('left')ax4.set_xlabel('x')ax4.set_ylabel('f(x)')ax4.set_title('Scatter Plot with Best Fit Line Figure')ax4.set_xlim((min(x)-1., max(x)+1.))ax4.set_ylim((min(y_quadratic)-10., max(y_quadratic)+10.))#散点图x_values = [1,2,3,4,5,6]y_values = [x**2 for x in x_values]ax5 = fig.add_subplot(3,2,5)#添加散点,c表示颜色,cmap=plt.cm.Blues表示颜色是渐变的蓝色#edgecolor表示圆点的便捷颜色,s表示圆点的大小ax5.scatter(x_values, y_values, c = y_values, cmap = plt.cm.Blues, \edgecolor = 'none', s = 40)ax5.xaxis.set_ticks_position('bottom')ax5.yaxis.set_ticks_position('left')ax5.set_xlabel('x')ax5.set_ylabel('f(x)')ax5.set_title('Scatter Figure')ax5.axis([0, max(x_values)+1, 0, max(y_values)+1])#箱线图N = 500normal = np.random.normal(loc = 0.0, scale = 1.0, size = N)lognormal = np.random.lognormal(mean = 0.0, sigma = 1.0, size = N)index_value = np.random.random_integers(low = 0, high = N-1, size = N)normal_sample = normal[index_value]lognormal_sample = lognormal[index_value]#添加箱型图box_plot_data = [normal, normal_sample, lognormal, lognormal_sample]box_labels = ['normal', 'normal_sample', 'lognormal', 'lognormal_sample']ax6 = fig.add_subplot(3,2,6)ax6.boxplot(box_plot_data, notch = False, sym = ',', vert = True, whis = 1.5, \showmeans = True, labels = box_labels)ax6.set_xticklabels(box_labels, rotation = 10)ax6.xaxis.set_ticks_position('bottom')ax6.yaxis.set_ticks_position('left')ax6.set_xlabel('Distribution')ax6.set_ylabel('Value')ax6.set_title('Box Plots: Resampling of Two Distribution')plt.tight_layout()#布局最优化,可防止图之间相互重叠plt.show()#展示图#保存图,参数分别表示:文件名、分辨率#bbox_inches='tight'表示去掉多余的白边,不想去掉可以忽略plt.savefig('hist_fig.png', dpi=400, bbox_inches = 'tight')

显示结果:

解决的问题:

六种图的创建方法;

更改图片的尺寸大小;

坐标轴标签倾斜角度;

颜色渐变;

图片之间重叠问题;

图例遮挡问题。

未解决的问题:

通过我这种方法实现多个条形图并列在一个坐标轴中的效果。如果有人知道麻烦告诉我,谢谢!!!

参考文献:

《Python数据分析基础》

《Python编程从入门到实践》

/shanger/p/13054285.html

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。