作業說明:
1、基於第二天實踐使用Python來爬去百度百科中《青春有你2》所有參賽選手的信息,進行數據可視化分析;
2、對《青春有你2》對選手體重分佈進行可視化,繪製餅狀圖
實現效果:
思路:
準備工作:
# 如果需要進行持久化安裝, 需要使用持久化路徑, 如下方代碼示例:
#!mkdir /home/aistudio/external-libraries
#!pip install matplotlib -t /home/aistudio/external-libraries
# 同時添加如下代碼, 這樣每次環境(kernel)啓動的時候只要運行下方代碼即可:
# Also add the following code, so that every time the environment (kernel) starts, just run the following code:
import sys
sys.path.append('/home/aistudio/external-libraries')
# 下載中文字體
!wget https://mydueros.cdn.bcebos.com/font/simhei.ttf
# 將字體文件複製到matplotlib字體路徑
!cp simhei.ttf /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/ttf/
# 一般只需要將字體文件複製到系統字體目錄下即可,但是在aistudio上該路徑沒有寫權限,所以此方法不能用
# !cp simhei.ttf /usr/share/fonts/
# 創建系統字體文件路徑
!mkdir .fonts
# 複製文件到該路徑
!cp simhei.ttf .fonts/
!rm -rf .cache/matplotlib
如果字體下載不了,就直接去官網下載到本地,然後上傳
GO:
繪製選手區域分佈柱狀圖:
import matplotlib.pyplot as plt
import numpy as np
import json
import matplotlib.font_manager as font_manager
import pandas as pd
#顯示matplotlib生成的圖形
%matplotlib inline
df = pd.read_json('data/data31557/20200422.json')
#print(df)
grouped=df['name'].groupby(df['zone'])
s = grouped.count()
zone_list = s.index
count_list = s.values
# 設置顯示中文
plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默認字體
plt.figure(figsize=(20,15))
plt.bar(range(len(count_list)), count_list,color='r',tick_label=zone_list,facecolor='#9999ff',edgecolor='white')
# 這裏是調節橫座標的傾斜度,rotation是度數,以及設置刻度字體大小
plt.xticks(rotation=45,fontsize=20)
plt.yticks(fontsize=20)
plt.legend()
plt.title('''《青春有你2》參賽選手''',fontsize = 24)
plt.savefig('/home/aistudio/work/result/bar_result02.jpg')
plt.show()
繪製餅狀圖:
import matplotlib.pyplot as plt
import numpy as np
import json
import matplotlib.font_manager as font_manager
#顯示matplotlib生成的圖形
%matplotlib inline
with open('data/data31557/20200422.json', 'r', encoding='UTF-8') as file:
json_array = json.loads(file.read())
#將參賽選手的體重放入列表
weight = []
for star in json_array: #遍歷每個明星並將她們的體重放在列表裏
weig = star['weight']
weight.append(weig)
print(len(weight)) #打印體重和人數
print(weight)
size1 = 0
size2 = 0
size3 = 0
size4 = 0
for num in weight:
if num <= '45kg':
size1 += 1
elif '45kg' < num <= '50kg':
size2 += 1
elif '50kg' < num <= '55kg':
size3 += 1
else:
size4 += 1
labels = ['<=45kg','45~50kg','50~55kg','>55kg'] #標籤
sizes = [size1, size2, size3, size4]
explode = (0.1,0.1,0,0)
fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode = explode, labels = labels, autopct='%1.1f%%', shadow=True)
ax1.axis('equal')
plt.savefig('/home/aistudio/work/result/pie_result01.jpg') #將餅圖存在目錄下
plt.show() #顯示餅圖
至此,數據分析成功!
♥ 喜 歡 請 點 贊 喲 ♥ |
(●ˇ∀ˇ●) |