欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

16、17、18_使用gridspec定义多子图,条形图(Bar plots),分组条形图,堆叠条形图(Stacked bar chart),饼图(Pie plots),甜甜圈图,嵌套饼图

发布时间:2024/9/27 编程问答 31 豆豆

16.使用gridspec定义多子图
16.1.图标题
17.条形图(Bar plots)
17.1.分组条形图
17.2.堆叠条形图(Stacked bar chart)
18.饼图(Pie plots)
18.1.甜甜圈图(Donut chart)
18.2.嵌套饼图 (Nested pie chart)

16.使用gridspec定义多子图

matplotlib.gridspec包含一个GridSpec类。它可以替代subplot来指定要创建的子图的几何布局。GridSpec背后的基本思路是”grid”。一个grid(网格)有多个行和列。必须在此之后定义个subplot应该跨越多少网格。

以下示例显示了最简单的情况,即1 * 1 grid。

import matplotlib.pyplot as plt from matplotlib.pyplot import GridSpec fig = plt.figure() gs = GridSpec(1, 1) ax = fig.add_subplot(gs[0, 0]) plt.show()

我们可以使用Gridspec的某些参数,例如, 可以定义图形从可用figure区域的底部的20%、左侧的15%开始:

import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec fig = plt.figure() gs = GridSpec(1, 1,bottom=0.2,left=0.15,top=0.8)ax = fig.add_subplot(gs[0,0]) plt.show()

下一个示例显示了一个更复杂的示例,其网络设计更加精细:
pyplot.figure用到的参数:
figsize(float, float), optional,default: None

width, height in inches. If not provided, defaults to rcParams[“figure.figsize”] (default: [6.4, 4.8]) = [6.4, 4.8].

import matplotlib.gridspec as gridspec import matplotlib.pyplot as pl pl.figure(figsize=(6, 4)) G = gridspec.GridSpec(3, 3) axes_1 = pl.subplot(G[0, :]) pl.xticks(()) pl.yticks(()) pl.text(0.5, 0.5, 'Axes 1', ha='center', va='center', size=24, alpha=.5) axes_2 = pl.subplot(G[1, :-1]) pl.xticks(()) pl.yticks(()) pl.text(0.5, 0.5, 'Axes 2', ha='center', va='center', size=24, alpha=.5) axes_3 = pl.subplot(G[1:, -1]) pl.xticks(()) pl.yticks(()) pl.text(0.5, 0.5, 'Axes 3', ha='center', va='center', size=24, alpha=.5) axes_4 = pl.subplot(G[-1, 0]) pl.xticks(()) pl.yticks(()) pl.text(0.5, 0.5, 'Axes 4', ha='center', va='center', size=24, alpha=.5) axes_5 = pl.subplot(G[-1, -2]) pl.xticks(()) pl.yticks(()) pl.text(0.5, 0.5, 'Axes 5', ha='center', va='center', size=24, alpha=.5) pl.tight_layout() pl.show()

现在,我们使用上一个示例中的grid specification(网格规范),以一些函数的图形填充它:

import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt import numpy as np plt.figure(figsize=(6, 4)) G = gridspec.GridSpec(3, 3) X = np.linspace(0, 2 * np.pi, 50, endpoint=True) F1 = 2.8 * np.cos(X) F2 = 5 * np.sin(X) F3 = 0.3 * np.sin(X) axes_1 = plt.subplot(G[0, :]) axes_1.plot(X, F1, 'r-', X, F2) axes_2 = plt.subplot(G[1, :-1]) axes_2.plot(X, F3) axes_3 = plt.subplot(G[1:, -1]) axes_3.plot([1,2,3,4], [1,10,100,1000], 'b-') axes_4 = plt.subplot(G[-1, 0]) axes_4.plot([1,2,3,4], [47, 11, 42, 60], 'r-') axes_5 = plt.subplot(G[-1, -2]) axes_5.plot([1,2,3,4], [7, 5, 4, 3.8]) plt.tight_layout() plt.show()

16.1.图标题

创建具有单独的subplot标题和居中figure标题的figure。

import matplotlib.pyplot as plt import numpy as npdef f(t):s1 = np.cos(2 * np.pi * t)e1 = np.exp(-t)return s1 * e1t1 = np.arange(0.0, 5.0, 0.1) t2 = np.arange(0.0, 5.0, 0.02) t3 = np.arange(0.0, 2.0, 0.01)fig, axs = plt.subplots(2, 1, constrained_layout=True) axs[0].plot(t1, f(t1), 'o', t2, f(t2), '-') axs[0].set_title('subplot 1') axs[0].set_xlabel('distance (m)') axs[0].set_ylabel('Damped oscillation') fig.suptitle('This is a somewhat long figure title', fontsize=16)axs[1].plot(t3, np.cos(2 * np.pi * t3), '--') axs[1].set_xlabel('time (s)') axs[1].set_title('subplot 2') axs[1].set_ylabel('Undamped')plt.show()

17.条形图(Bar plots)

条形图是用矩形条形显示分类数据,其高度或长度与其所代表的值成正比。
条形图可以垂直或水平绘制。

适用时机:
•比较分类数据
•离散类别之间的比较
•图表的一个轴显示要比较的特定类别,另一个轴代表测量值。

pyplot.bar定义文档:plot.bar

import matplotlib.pyplot as pltbars = plt.bar([1, 2, 3, 4], [1, 4, 9, 16]) bars[0].set_color('green')plt.show()

import matplotlib.pyplot as pltf = plt.figure() ax = f.add_subplot(1, 1, 1) ax.bar([1, 2, 3, 4], [1, 4, 9, 16]) children = ax.get_children() children[3].set_color('g')plt.show() import matplotlib.pyplot as plt import numpy as np years = ('2015', '2016', '2017', '2018', '2019') visitors = (1241, 50927, 162242, 222093, 296665 / 8 * 12) index = np.arange(len(visitors)) bar_width = 1.0 plt.bar(index, visitors, bar_width, color="green") plt.xticks(index + bar_width / 2, years) # labels get centered plt.show()

17.1.分组条形图

条形图还可以用于分组条形图和堆叠条形图的更复杂的数据比较。 在分组的条形图中,对于每个类别组,都有两个或多个条形。 这些条用不同的颜色表示特定的分组。

import matplotlib.pyplot as plt import numpy as nplabels = ['G1', 'G2', 'G3', 'G4', 'G5'] men_means = [20, 34, 30, 35, 27] women_means = [25, 32, 34, 20, 25]x = np.arange(len(labels)) # the label locations width = 0.35 # the width of the barsfig, ax = plt.subplots() rects1 = ax.bar(x - width / 2, men_means, width, label='Men') rects2 = ax.bar(x + width / 2, women_means, width, label='Women')# Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Scores') ax.set_title('Scores by group and gender') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend()def autolabel(rects):"""Attach a text label above each bar in *rects*, displaying its height."""for rect in rects:height = rect.get_height()ax.annotate('{}'.format(height),xy=(rect.get_x() + rect.get_width() / 2, height),xytext=(0, 3), # 3 points vertical offsettextcoords="offset points",ha='center', va='bottom')autolabel(rects1) autolabel(rects2)fig.tight_layout()plt.show()

17.2.堆叠条形图(Stacked bar chart)

堆叠的条形图将代表不同组的条形图堆叠在一起。 条的高度显示了这些组的组合结果。

适用时机:
•比较总数(total)和总数的一部分。
•如果组成部分的总数(total)至关重要,则堆叠的柱形图可以很好地适用。

下面是使用bar创建带有误差线的堆叠条形图的示例。 请注意用于误差线的参数yerr,并在底部将Women条堆叠在Men条的顶部。

import matplotlib.pyplot as pltlabels = ['G1', 'G2', 'G3', 'G4', 'G5'] men_means = [20, 35, 30, 35, 27] women_means = [25, 32, 34, 20, 25] men_std = [2, 3, 4, 1, 2] women_std = [3, 5, 2, 3, 3] width = 0.35 # the width of the bars: can also be len(x) sequencefig, ax = plt.subplots()ax.bar(labels, men_means, width, yerr=men_std, label='Men') ax.bar(labels, women_means, width, yerr=women_std, bottom=men_means,label='Women')ax.set_ylabel('Scores') ax.set_title('Scores by group and gender') ax.legend()plt.show()

18.饼图(Pie plots)

饼图是圆形统计图形,将其分成多个切片以说明数字比例。 在饼图中,每个切片的弧长(以及其中心角和面积)均与其表示的量成比例。

适用时机:
显示百分比或比例数据
显示分类数据
使用正值

下面演示基本的饼图,还显示了一些可选功能:
切片标签
自动标记百分比
用”爆炸”偏移切片
阴影
自定义起始角度

关于自定义起始角度的注意事项:默认起始角度为0,它将在正x轴上开始"Frogs"切片。 本示例将startangle = 90设置为使所有内容都逆时针旋转90度,并且"Frogs"切片从y轴正方向开始。

import matplotlib.pyplot as plt# Pie chart, where the slices will be ordered and plotted counter-clockwise: labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' sizes = [15, 30, 45, 10] explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')fig1, ax1 = plt.subplots() ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',shadow=True, startangle=90) ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.plt.show()


参数说明:
x :(每一块)的比例,如果sum(x) > 1会使用sum(x)归一化;
labels :(每一块)饼图外侧显示的说明文字;
explode :(每一块)离开中心距离;
startangle :起始绘制角度,默认图是从x轴正方向逆时针画起,如设定=90则从y轴正方向画起;
shadow :在饼图下面画一个阴影。默认值:False,即不画阴影;
labeldistance :label标记的绘制位置,相对于半径的比例,默认值为1.1, 如<1则绘制在饼图内侧;
autopct :控制饼图内百分比设置,可以使用format字符串或者format function;’%1.1f’指小数点前后位数(没有用空格补齐);
pctdistance :类似于labeldistance,指定autopct的位置刻度,默认值为0.6;
radius :控制饼图半径,默认值为1;counterclock :指定指针方向;布尔值,可选参数,默认为:True,即逆时针。将值改为False即可改为顺时针。
wedgeprops :字典类型,可选参数,默认值:None。参数字典传递给wedge对象用来画一个饼图。例如:wedgeprops={‘linewidth’:3}设置wedge线宽为3。
textprops :设置标签(labels)和比例文字的格式;字典类型,可选参数,默认值为:None。传递给text对象的字典参数。
center :浮点类型的列表,可选参数,默认值:(0,0)。图标中心位置。
frame :布尔类型,可选参数,默认值:False。如果是true,绘制带有表的轴框架。
rotatelabels :布尔类型,可选参数,默认为:False。如果为True,旋转每个label到指定的角度。

import matplotlib.pyplot as pltlabels = 'apple', 'banana', 'cherry', 'durian', 'elderberries', 'figs', 'grapes' sizes = [32, 20, 15, 10, 10, 8, 5]p = plt.pie(sizes, labels=labels, explode=(0.07, 0, 0, 0, 0, 0, 0),autopct='%1.1f%%', startangle=120, shadow=True)plt.axis('equal')for i, (apple, banana, cherry, durian, elderberries, figs, grapes) in enumerate(p):if i > 0:apple.set_fontsize(12)banana.set_fontsize(12)cherry.set_fontsize(12)durian.set_fontsize(12)elderberries.set_fontsize(12)figs.set_fontsize(12)grapes.set_fontsize(12)plt.show()

此饼图描述了每种水果的营业百分比。苹果销售是7个水果中营业额最高的,占营业额的32%。

18.1.甜甜圈图(Donut chart)

甜甜圈图是饼图的一种变体,中间有一个空白的中心,允许包含有关整个数据的其他信息。

import matplotlib.pyplot as pltlabels = 'apple', 'banana', 'cherry', 'durian', 'elderberries', 'figs', 'grapes' sizes = [32, 20, 15, 10, 10, 8, 5]my_circle = plt.Circle((0, 0), 0.7, color='white') d = plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90, labeldistance=1.05)plt.axis('equal') plt.gca().add_artist(my_circle)plt.show()

18.2.嵌套饼图 (Nested pie chart)

嵌套饼图或多级饼图可让你将多个级别或层包含到饼图中。
适用时机:
在合并的饼状结构中显示对称和不对称的树结构。
多层数据表示,例如关键字分析
相互关联的树数据,例如,朋友的朋友

sizes = [300, 200] labels_vegefruit = ['potato', 'tomato', 'onion', 'apple','banana', 'cherry', 'durian'] sizes_vegefruit = [170, 70, 60, 70, 60, 50, 20] colors = ['#FFB600', '#09A0DA'] colors_vegefruit = ['#FFCE53', '#FFDA7E', '#FFE9B2', '#30B7EA','#56C7F2', '#7FD6F7', '#B3E7FB']bigger = plt.pie(sizes, labels=labels, colors=colors,startangle=90, frame=True) smaller = plt.pie(sizes_vegefruit, labels=labels_vegefruit,colors=colors_vegefruit, radius=0.7,startangle=90, labeldistance=0.7) centre_circle = plt.Circle((0, 0), 0.4, color='white', linewidth=0) fig = plt.gcf() fig.gca().add_artist(centre_circle)plt.axis('equal') plt.tight_layout()plt.show()

总结

以上是生活随笔为你收集整理的16、17、18_使用gridspec定义多子图,条形图(Bar plots),分组条形图,堆叠条形图(Stacked bar chart),饼图(Pie plots),甜甜圈图,嵌套饼图的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。