前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >这几个Matplotlib绘图技巧,真的是太实用了

这几个Matplotlib绘图技巧,真的是太实用了

作者头像
用户6888863
发布2023-03-01 20:18:50
2450
发布2023-03-01 20:18:50
举报
文章被收录于专栏:AI篮球与生活AI篮球与生活

今天呢,小编来为大家分享几个用matplotlib模块绘制图表的小技巧,希望看了之后会对大家有不少的帮助!!

在图表中插入图片

如果我们想要在绘制的图表中插入图片,具体该怎么来实现呢?!需要用到的数据集如下图所示

代码语言:javascript
复制
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

我们首先来绘制一张简单的图表,代码如下所示

代码语言:javascript
复制
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(),我们需要插入的图片如下图所示,

代码语言:javascript
复制
import matplotlib.image as image

logo = image.imread("logo1.png")
plt.imshow(logo)
plt.show()

output

那么要将图片添加到图表中去的话,调用的是OffsetImage模块和AnnotationBbox模块,首先我们将图片元素放入到OffsetImage当中去,并且调整放大缩小的比例,然后再是调用AnnotationBbox模块来确定添加图片的具体位置,代码如下

代码语言:javascript
复制
from matplotlib.offsetbox import (OffsetImage, AnnotationBbox)

imagebox = OffsetImage(logo, zoom = 0.15)
ab = AnnotationBbox(imagebox, (5, 700), frameon = False)
ax.add_artist(ab)

整体的代码如下所示

代码语言:javascript
复制
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制作动图

那之前小编来写过相制作动图的相类似的文章,有兴趣的读者朋友可以点击下面的链接查阅。

- 用Python绘制超酷的gif动图,惊艳了所有人

其实用matplotlib模块来制作动图则十分的方便,效果如下图所示

首先的第一步是创建一个自定义函数来绘制不同时间节点的图表,代码如下

代码语言:javascript
复制
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()

我们调用上述的自定义函数来绘制不同时间节点的图表,代码如下

代码语言:javascript
复制
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动图即可,代码如下

代码语言:javascript
复制
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)
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2022-10-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 关于数据分析与可视化 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 在图表中插入图片
  • 用Matplotlib制作动图
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档