이전 기사에서 편집자는 Python
gif
만들기 위한 모듈gif
형식 차트는 Python
当中的gif
模块来制作gif
格式的图表,
厉害了,用Python绘制动态可视化图表,并保存成gif格式今天小编再给大家来介绍一种制作gif
格式图表的新方法,调用的是matplotlib
的相关模块,其中的步骤与方法也是相当地简单易懂。
我们这次用到的数据集是bokeh
模块自带的数据集,通过下面这一行代码直接就可以下载
import bokeh bokeh.sampledata.download()
然后导入后面要用到的数据集,我们挑选的是指定国家的1950年至今不同年龄阶段的人口所占比重的数据
from bokeh.sampledata.population import data import numpy as np data = filter_loc('United States of America') data.head()
output
我们可以先绘制若干张静态的图表,然后将这几张图表合成一张gif
格式的动图即可,代码如下
import seaborn as sns import matplotlib.pyplot as plt import matplotlib.patheffects as fx # 绘制图表的函数 def make_plot(year): # 根据年份来筛选出数据 df = data[data.Year == year] # 制作图表 fig, (ax1, ax2) = plt.subplots(1, 2, sharey = True) ax1.invert_xaxis() fig.subplots_adjust(wspace = 0) ax1.barh(df[df.Sex == 'Male'].AgeGrp, df[df.Sex == 'Male'].percent, label = 'Male') ax2.barh(df[df.Sex == 'Female'].AgeGrp, df[df.Sex == 'Female'].percent, label = 'Female', color = 'C1') country = df.Location.iloc[0] if country == 'United States of America': country == 'US' fig.suptitle(f'......') fig.supxlabel('......') fig.legend(bbox_to_anchor = (0.9, 0.88), loc = 'upper right') ax1.set_ylabel('Age Groups') return fig
我们自定义了一个绘制图表的函数,其中的参数是年份,逻辑很简单,我们是想根据年份来筛选出数据,然后根据筛选出的数据来绘制图表,每一年的图表不尽相同
years = [i for i in set(data.Year) if i < 2022] years.sort() for year in years: fig = make_plot(year) fig.savefig(f'{year}.jpeg',bbox_inches = 'tight')
output
这样我们就生成了若干张静态的图表,然后集合成gif
gif 차트 서식 지정, <code style="font-family: monospace; 글꼴 크기: 상속; 배경색: rgba(0, 0, 0, 0.06); 패딩: 0px 2px; 테두리 반경: 6px; 라인- height: 상속; Overflow-wrap: break-word; text-indent: 0px;">matplotlib
관련 모듈, 단계 및 방법도 매우 유사하여 이해하기 쉽습니다.
데이터베이스 다운로드 및 가져오기 이번에 사용한 데이터 세트는
import matplotlib.animation as animation
fig, ax = plt.subplots()
ims = []
for year in years:
im = ax.imshow(plt.imread(f'{year}.jpeg'), animated = True)
ims.append([im])
ani = animation.ArtistAnimation(fig, ims, interval=600)
ani.save('us_population.gif')
</pre><h3 >를 통해 직접 다운로드한 다음 나중에 사용할 데이터 세트로 가져올 수 있습니다. 1950년부터 현재까지의 비중 데이터<span style=" color:><pre class="brush:python;toolbar:false;">fig, (ax1, ax2) = plt.subplots(1, 2, sharey = True)
df = data[data.Year == 1955]
y_pos = [i for i in range(len(df[df.Sex == 'Male']))]
male = ax1.barh(y_pos, df[df.Sex == 'Male'].percent, label = 'Male',
tick_label = df[df.Sex == 'Male'].AgeGrp)
female = ax2.barh(y_pos, df[df.Sex == 'Female'].percent, label = 'Female',
color = 'C1', tick_label = df[df.Sex == 'Male'].AgeGrp)
ax1.invert_xaxis()
fig.suptitle('.......')
fig.supxlabel('....... (%)')
fig.legend(bbox_to_anchor = (0.9, 0.88), loc = 'upper right')
ax1.set_ylabel('Age Groups')
</pre>
def run(year):
# 通过年份来筛选出数据
df = data[data.Year == year]
# 针对不同地性别来绘制
total_pop = df.Value.sum()
df['percent'] = df.Value / total_pop * 100
male.remove()
y_pos = [i for i in range(len(df[df.Sex == 'Male']))]
male.patches = ax1.barh(y_pos, df[df.Sex == 'Male'].percent, label = 'Male',
color = 'C0', tick_label = df[df.Sex == 'Male'].AgeGrp)
female.remove()
female.patches = ax2.barh(y_pos, df[df.Sex == 'Female'].percent, label = 'Female',
color = 'C1', tick_label = df[df.Sex == 'Female'].AgeGrp)
text.set_text(year)
return male#, female
</pre></p>차트를 그리는 기능을 사용자 정의했습니다. 논리는 매우 간단합니다. Year를 선택하여 데이터를 필터링한 다음, 필터링된 데이터를 기반으로 차트를 그립니다. 각 연도의 차트는 다릅니다🎜<pre class="brush:python;toolbar:false;">ani = animation.FuncAnimation(fig, run, years, blit = True, repeat = True,
interval = 600)
ani.save('文件名.gif')
</pre>🎜output🎜🎜<img src=" data-src="https://img.php.cn/upload/article/000/887/227/168318834978200.gif" class="lazy" alt="Python을 사용하여 모두를 놀라게 하는 멋진 gif 애니메이션을 그립니다.">
🎜🎜이러한 방식으로 여러 정적 차트를 생성한 다음 이를 gif
형식의 여러 차트, 코드는 다음과 같습니다🎜import matplotlib.animation as animation # 创建一个新的画布 fig, (ax, ax2, ax3) = plt.subplots(1, 3, figsize = (10, 3)) ims = [] for year in years: im = ax.imshow(plt.imread(f'文件1{year}.jpeg'), animated = True) im2 = ax2.imshow(plt.imread(f'文件2{year}.jpeg'), animated = True) im3 = ax3.imshow(plt.imread(f'文件3{year}.jpeg'), animated = True) ims.append([im, im2, im3]) ani = animation.ArtistAnimation(fig, ims, interval=600) ani.save('comparison.gif')🎜output🎜🎜🎜🎜🎜🎜🎜여기에서 볼 수 있는 또 다른 아이디어가 있습니다. , 어떤 사람들은 위에서 언급한 방법이 약간 번거롭다고 생각할 수도 있습니다. 결국, 컴퓨터의 디스크 공간이 조금 부족하거나 이러한 수십 개를 저장할 공간이 없다면 먼저 수십 개의 정적 차트를 생성해야 합니다. 차트. 그렇다면 한 단계로 완료할 수 있는지 궁금할 것입니다. 물론 가능하다. 예를 들어 1950년부터 2020년까지 연령별 인구비율 분포를 도출할 계획이라면, 첫 번째 단계는 시작연도인 1950년을 기준으로 연령별 인구비율 분포를 도출하는 것이다. 그림, 코드는 다음과 같습니다🎜rrreee🎜output🎜🎜🎜🎜🎜 그런 다음 차트를 그리는 함수를 사용자 정의합니다. 여기서 매개 변수는 연도이며, 목적은 해당 데이터를 연도별로 필터링하여 해당 차트를 그리는 것입니다🎜
def run(year): # 通过年份来筛选出数据 df = data[data.Year == year] # 针对不同地性别来绘制 total_pop = df.Value.sum() df['percent'] = df.Value / total_pop * 100 male.remove() y_pos = [i for i in range(len(df[df.Sex == 'Male']))] male.patches = ax1.barh(y_pos, df[df.Sex == 'Male'].percent, label = 'Male', color = 'C0', tick_label = df[df.Sex == 'Male'].AgeGrp) female.remove() female.patches = ax2.barh(y_pos, df[df.Sex == 'Female'].percent, label = 'Female', color = 'C1', tick_label = df[df.Sex == 'Female'].AgeGrp) text.set_text(year) return male#, female
然后我们调用animation.FuncAnimation()
方法,
ani = animation.FuncAnimation(fig, run, years, blit = True, repeat = True, interval = 600) ani.save('文件名.gif')
output
这样就可以一步到位生成gif
格式的图表,避免生成数十张繁多地静态图片了。
<span style="color: #2b2b2b;">gif</span>
动图放置在一张大图当中
最后我们可以将若干张gif
动图放置在一张大的图表当中,代码如下
import matplotlib.animation as animation # 创建一个新的画布 fig, (ax, ax2, ax3) = plt.subplots(1, 3, figsize = (10, 3)) ims = [] for year in years: im = ax.imshow(plt.imread(f'文件1{year}.jpeg'), animated = True) im2 = ax2.imshow(plt.imread(f'文件2{year}.jpeg'), animated = True) im3 = ax3.imshow(plt.imread(f'文件3{year}.jpeg'), animated = True) ims.append([im, im2, im3]) ani = animation.ArtistAnimation(fig, ims, interval=600) ani.save('comparison.gif')
output
위 내용은 Python을 사용하여 모두를 놀라게 할 멋진 gif 애니메이션을 그려보세요.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!