今天呢,小编来为大家分享几个用matplotlib
模块绘制图表的小技巧,希望看了之后会对大家有不少的帮助!!
如果我们想要在绘制的图表中插入图片,具体该怎么来实现呢?!需要用到的数据集如下图所示
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.size'] = 14
df = pd.DataFrame()
df["Years"] = [2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021]
df["Installed Capacity (GW)"] = [72, 102, 137, 176, 223, 295, 390, 483, 585, 710, 843]
df.set_index("Years", inplace = True)
df
output
我们首先来绘制一张简单的图表,代码如下所示
fig, ax = plt.subplots(figsize = (12, 8))
df.plot(kind = "bar", ax = ax)
plt.ylabel("GW")
# Remove legend along with the frame
plt.legend([], frameon = False)
plt.title("Global Installed Capacity of Solar PV")
# Hide the right and top spines
ax.spines.right.set_visible(False)
ax.spines.top.set_visible(False)
# Set xticks rotation to 0
plt.xticks(rotation = 0)
# Add grid line
plt.grid(axis = "y")
# Adding value labels on top of bars
for i in range(len(df)):
installed = df.iloc[i][0]
plt.text(x = i - 0.2,y = installed + 5,
s = str(installed))
# Add source
plt.text(8, -100, "Source: IRENA, 2022")
plt.show()
output
从上面的代码中我们看出,如果是往图表中添加文字注释,调用的函数是plt.text()
,我们需要插入的图片如下图所示,
import matplotlib.image as image
logo = image.imread("logo1.png")
plt.imshow(logo)
plt.show()
output
那么要将图片添加到图表中去的话,调用的是OffsetImage
模块和AnnotationBbox
模块,首先我们将图片元素放入到OffsetImage
当中去,并且调整放大缩小的比例,然后再是调用AnnotationBbox
模块来确定添加图片的具体位置,代码如下
from matplotlib.offsetbox import (OffsetImage, AnnotationBbox)
imagebox = OffsetImage(logo, zoom = 0.15)
ab = AnnotationBbox(imagebox, (5, 700), frameon = False)
ax.add_artist(ab)
整体的代码如下所示
import matplotlib.image as image
from matplotlib.offsetbox import (OffsetImage, AnnotationBbox)
fig, ax = plt.subplots(figsize = (12, 8))
df.plot(kind = "bar", ax = ax)
imagebox = OffsetImage(logo, zoom = 0.5)
ab = AnnotationBbox(imagebox, (5, 700), frameon = False)
ax.add_artist(ab)
plt.ylabel("GW")
# 标题
plt.title("Global Installed Capacity of Solar PV")
ax.spines.right.set_visible(False)
ax.spines.top.set_visible(False)
# 添加横线
plt.grid(axis = "y")
# 柱状图上添加注释
for i in range(len(df)):
installed = df.iloc[i][0]
plt.text(x = i - 0.2,
y = installed + 5,
s = str(installed))
# 添加注释
plt.text(8, -100, "Source: IRENA, 2022")
plt.show()
output
Matplotlib
制作动图那之前小编来写过相制作动图的相类似的文章,有兴趣的读者朋友可以点击下面的链接查阅。
其实用matplotlib
模块来制作动图则十分的方便,效果如下图所示
首先的第一步是创建一个自定义函数来绘制不同时间节点的图表,代码如下
def create_frame(t):
fig = plt.figure(figsize=(6, 6))
plt.plot(x[:(t+1)], y[:(t+1)], color = 'grey' )
plt.plot(x[t], y[t], color = 'black', marker = 'o' )
plt.xlim([0,5])
plt.xlabel('x', fontsize = 14)
plt.ylim([0,5])
plt.ylabel('y', fontsize = 14)
plt.title(f'Relationship between x and y at step {t}',
fontsize=14)
plt.savefig(f'img_{t}.png',
transparent = False,
facecolor = 'white'
)
plt.show()
plt.close()
我们调用上述的自定义函数来绘制不同时间节点的图表,代码如下
x = [1, 2, 3, 4, 4, 4, 4, 3, 2, 1, 1, 1, 1]
y = [1, 1, 1, 1, 2, 3, 4, 4, 4, 4, 3, 2, 1]
time = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
for t in time:
create_frame(t)
output
最后我们将所有绘制出来的图表结合到一起,制作成gif
动图即可,代码如下
frames = []
for image_name in ["img_0.png", "img_1.png", "img_2.png", "img_3.png", "img_4.png", "img_5.png",
"img_6.png", "img_7.png", "img_8.png", "img_9.png", "img_10.png", "img_11.png", "img_12.png"]:
frames.append(imageio.imread(image_name))
imageio.mimsave('example.gif',
frames,
fps = 5)