可视化图表有很多种,这篇文章主要介绍了Python绘制六种可视化图表详解的方法,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
可视化图表,有相当多种,但常见的也就下面几种,其他比较复杂一点,大都也是基于如下几种进行组合,变换出来的。对于初学者来说,很容易被这官网上众多的图表类型给吓着了,由于种类太多,几种图表的绘制方法很有可能会混淆起来。
因此,在这里,我特地总结了六种常见的基本图表类型,你可以通过对比学习,打下坚实的基础。
01. 折线图
绘制折线图,如果你数据不是很多的话,画出来的图将是曲折状态,但一旦你的数据集大起来,比如下面我们的示例,有100个点,所以我们用肉眼看到的将是一条平滑的曲线。
这里我绘制三条线,只要执行三次 plt.plot 就可以了。
1 2 3 4 5 6 7 8 9 10 11 | import numpy as np import matplotlib.pyplot as plt x = np.linspace( 0 , 2 , 100 ) plt.plot(x, x, label = 'linear' ) plt.plot(x, x * * 2 , label = 'quadratic' ) plt.plot(x, x * * 3 , label = 'cubic' ) plt.xlabel( 'x label' ) plt.ylabel( 'y label' ) plt.title( "Simple Plot" ) plt.legend() plt.show() |
![](https://i-blog.csdnimg.cn/blog_migrate/c7e4c51b634ce0f9d0ee660578aadca1.png)
02. 散点图
其实散点图和折线图是一样的原理,将散点图里的点用线连接起来就是折线图了。所以绘制散点图,只要设置一下线型即可。
注意:这里我也绘制三条线,和上面不同的是,我只用一个 plt.plot 就可以了。
1 2 3 4 5 6 | import numpy as np import matplotlib.pyplot as plt x = np.arange( 0. , 5. , 0.2 ) # 红色破折号, 蓝色方块 ,绿色三角块 plt.plot(x, x, 'r--' , x, x * * 2 , 'bs' , x, x * * 3 , 'g^' ) plt.show() |
![](https://i-blog.csdnimg.cn/blog_migrate/f2ab1f465ee7ec80623aec2eb2bedee5.png)
03. 直方图
直方图,大家也不算陌生了。这里小明加大难度,在一张图里,画出两个频度直方图。这应该在实际场景上也会遇到吧,因为这样真的很方便比较,有木有?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import numpy as np import matplotlib.pyplot as plt np.random.seed( 19680801 ) mu1, sigma1 = 100 , 15 mu2, sigma2 = 80 , 15 x1 = mu1 + sigma1 * np.random.randn( 10000 ) x2 = mu2 + sigma2 * np.random.randn( 10000 ) # the histogram of the data # 50:将数据分成50组 # facecolor:颜色;alpha:透明度 # density:是密度而不是具体数值 n1, bins1, patches1 = plt.hist(x1, 50 , density = True , facecolor = 'g' , alpha = 1 ) n2, bins2, patches2 = plt.hist(x2, 50 , density = True , facecolor = 'r' , alpha = 0.2 ) # n:概率值;bins:具体数值;patches:直方图对象。 plt.xlabel( 'Smarts' ) plt.ylabel( 'Probability' ) plt.title( 'Histogram of IQ' ) plt.text( 110 , . 025 , r '$\mu=100,\ \sigma=15$' ) plt.text( 50 , . 025 , r '$\mu=80,\ \sigma=15$' ) # 设置x,y轴的具体范围 plt.axis([ 40 , 160 , 0 , 0.03 ]) plt.grid( True ) plt.show() |
![](https://i-blog.csdnimg.cn/blog_migrate/2894360166d51df496436f851eb1c899.png)
04. 柱状图
同样的,简单的柱状图,我就不画了,这里画三种比较难的图。
4.1 并列柱状图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import numpy as np import matplotlib.pyplot as plt size = 5 a = np.random.random(size) b = np.random.random(size) c = np.random.random(size) x = np.arange(size) # 有多少个类型,只需更改n即可 total_width, n = 0.8 , 3 width = total_width / n # 重新拟定x的坐标 x = x - (total_width - width) / 2 # 这里使用的是偏移 plt.bar(x, a, width = width, label = 'a' ) plt.bar(x + width, b, width = width, label = 'b' ) plt.bar(x + 2 * width, c, width = width, label = 'c' ) plt.legend() plt.show() |
![](https://i-blog.csdnimg.cn/blog_migrate/994548b66b0fe9830ec6be10178b5086.png)
4.2 叠加柱状图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import numpy as np import matplotlib.pyplot as plt size = 5 a = np.random.random(size) b = np.random.random(size) c = np.random.random(size) x = np.arange(size) # 这里使用的是偏移 plt.bar(x, a, width = 0.5 , label = 'a' ,fc = 'r' ) plt.bar(x, b, bottom = a, width = 0.5 , label = 'b' , fc = 'g' ) plt.bar(x, c, bottom = a + b, width = 0.5 , label = 'c' , fc = 'b' ) plt.ylim( 0 , 2.5 ) plt.legend() plt.grid( True ) plt.show() |
![](https://i-blog.csdnimg.cn/blog_migrate/6bc7c5e994e17b8c26c8b5702f3fe7c3.png)
05. 饼图
5.1 普通饼图
1 2 3 4 5 6 7 8 9 10 | import matplotlib.pyplot as plt labels = 'Frogs' , 'Hogs' , 'Dogs' , 'Logs' sizes = [ 15 , 30 , 45 , 10 ] # 设置分离的距离,0表示不分离 explode = ( 0 , 0.1 , 0 , 0 ) plt.pie(sizes, explode = explode, labels = labels, autopct = '%1.1f%%' , shadow = True , startangle = 90 ) # Equal aspect ratio 保证画出的图是正圆形 plt.axis( 'equal' ) plt.show() |
![](https://i-blog.csdnimg.cn/blog_migrate/4aa7d2675b2ef77bf134687d2eca7ad1.png)
5.2 嵌套饼图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import numpy as np import matplotlib.pyplot as plt # 设置每环的宽度 size = 0.3 vals = np.array([[ 60. , 32. ], [ 37. , 40. ], [ 29. , 10. ]]) # 通过get_cmap随机获取颜色 cmap = plt.get_cmap( "tab20c" ) outer_colors = cmap(np.arange( 3 ) * 4 ) inner_colors = cmap(np.array([ 1 , 2 , 5 , 6 , 9 , 10 ])) print (vals. sum (axis = 1 )) # [92. 77. 39.] plt.pie(vals. sum (axis = 1 ), radius = 1 , colors = outer_colors, wedgeprops = dict (width = size, edgecolor = 'w' )) print (vals.flatten()) # [60. 32. 37. 40. 29. 10.] plt.pie(vals.flatten(), radius = 1 - size, colors = inner_colors, wedgeprops = dict (width = size, edgecolor = 'w' )) # equal 使得为正圆 plt.axis( 'equal' ) plt.show() |
![](https://i-blog.csdnimg.cn/blog_migrate/df260c0519597d5db78f5351826708fe.png)
5.3 极轴饼图
要说酷炫,极轴饼图也是数一数二的了,这里肯定也要学一下。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import numpy as np import matplotlib.pyplot as plt np.random.seed( 19680801 ) N = 10 theta = np.linspace( 0.0 , 2 * np.pi, N, endpoint = False ) radii = 10 * np.random.rand(N) width = np.pi / 4 * np.random.rand(N) ax = plt.subplot( 111 , projection = 'polar' ) bars = ax.bar(theta, radii, width = width, bottom = 0.0 ) # left表示从哪开始, # radii表示从中心点向边缘绘制的长度(半径) # width表示末端的弧长 # 自定义颜色和不透明度 for r, bar in zip (radii, bars): bar.set_facecolor(plt.cm.viridis(r / 10. )) bar.set_alpha( 0.5 ) plt.show() |
![](https://i-blog.csdnimg.cn/blog_migrate/10f5c039c3cbda0568056d2bf77599db.png)
06. 三维图
6.1 绘制三维散点图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D data = np.random.randint( 0 , 255 , size = [ 40 , 40 , 40 ]) x, y, z = data[ 0 ], data[ 1 ], data[ 2 ] ax = plt.subplot( 111 , projection = '3d' ) # 创建一个三维的绘图工程 # 将数据点分成三部分画,在颜色上有区分度 ax.scatter(x[: 10 ], y[: 10 ], z[: 10 ], c = 'y' ) # 绘制数据点 ax.scatter(x[ 10 : 20 ], y[ 10 : 20 ], z[ 10 : 20 ], c = 'r' ) ax.scatter(x[ 30 : 40 ], y[ 30 : 40 ], z[ 30 : 40 ], c = 'g' ) ax.set_zlabel( 'Z' ) # 坐标轴 ax.set_ylabel( 'Y' ) ax.set_xlabel( 'X' ) plt.show() |
![](https://i-blog.csdnimg.cn/blog_migrate/98b8e3149306e749a04feedcdde1bea1.png)
6.2 绘制三维平面图
1 2 3 4 5 6 7 8 9 10 11 12 13 | from matplotlib import pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = Axes3D(fig) X = np.arange( - 4 , 4 , 0.25 ) Y = np.arange( - 4 , 4 , 0.25 ) X, Y = np.meshgrid(X, Y) R = np.sqrt(X * * 2 + Y * * 2 ) Z = np.sin(R) # 具体函数方法可用 help(function) 查看,如:help(ax.plot_surface) ax.plot_surface(X, Y, Z, rstride = 1 , cstride = 1 , cmap = 'rainbow' ) plt.show() |
![](https://i-blog.csdnimg.cn/blog_migrate/17b3b287128b677b1fb0dbb00653181f.png)
总结
以上所述是小编给大家介绍的Python绘制六种可视化图表,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
====================================================
1、堆叠柱状图
[python] view plain copy
- # -*- coding: utf-8 -*-
- import matplotlib.pyplot as plt
-
- name_list = ['Monday','Tuesday','Friday','Sunday']
- num_list = [1.5,0.6,7.8,6]
- num_list1 = [1,2,3,1]
- plt.bar(range(len(num_list)), num_list, label='boy',fc = 'y')
- plt.bar(range(len(num_list)), num_list1, bottom=num_list, label='girl',tick_label = name_list,fc = 'r')
- plt.legend()
- plt.show()
![](https://i-blog.csdnimg.cn/blog_migrate/298b58866318d9648d47a0f35d2c48c7.png)
2、并列柱状图
[python] view plain copy
- # -*- coding: utf-8 -*-
- import matplotlib.pyplot as plt
-
- name_list = ['Monday','Tuesday','Friday','Sunday']
- num_list = [1.5,0.6,7.8,6]
- num_list1 = [1,2,3,1]
- x =list(range(len(num_list)))
- total_width, n = 0.8, 2
- width = total_width / n
-
- plt.bar(x, num_list, width=width, label='boy',fc = 'y')
- for i in range(len(x)):
- x[i] = x[i] + width
- plt.bar(x, num_list1, width=width, label='girl',tick_label = name_list,fc = 'r')
- plt.legend()
- plt.show()
![](https://i-blog.csdnimg.cn/blog_migrate/f1405da6aa38aa513eff4b1f8635d111.png)
3、条形柱状图
[python] view plain copy
- # -*- coding: utf-8 -*-
- import matplotlib.pyplot as plt
-
- name_list = ['Monday','Tuesday','Friday','Sunday']
- num_list = [1.5,0.6,7.8,6]
- plt.barh(range(len(num_list)), num_list,tick_label = name_list)
- plt.show()
![](https://i-blog.csdnimg.cn/blog_migrate/cad1c46518eca73744b17fe91cf20024.png)
![复制代码](https://i-blog.csdnimg.cn/blog_migrate/3261cce84d531bb17b20112813d07e17.gif)
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams["font.sans-serif"] = ["SimHei"]
mpl.rcParams["axes.unicode_minus"] = False
elements = ["面粉", "砂糖", "奶油", "草莓酱", "坚果"]
weight = [40, 15, 20, 10, 15]
colors = ["#377eb8", "#4daf4a", "#984ea3", "#ff7f00", "#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.setp(autotexts, size=15, weight="bold")
plt.setp(texts, size=12)
plt.title("果酱面料配料比例表")
plt.show()
![复制代码](https://i-blog.csdnimg.cn/blog_migrate/3261cce84d531bb17b20112813d07e17.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/8f4b8d2333d923574ba3ba43a72a84e9.png)