栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python数据分析--plt条形图的绘制

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python数据分析--plt条形图的绘制

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import re
import os
from PIL import Image
from pyecharts.charts import Pie
from pyecharts import options as opts
from pyecharts.globals import CurrentConfig, NotebookType
CurrentConfig.NOTEBOOK_TYPE = NotebookType.JUPYTER_LAB
#%matplotlib inline
pd.set_option("display.max_column",None)
sns.set_style('white',{'font.sans-serif':['simhei','Arial']})

df_season = pd.read_pickle("./season.pkl")

df_season.rename(columns={"出手":"总出手","命中":"总命中","命中.1":"三分命中","出手.1":"三分出手","命中.2":"罚球命中","出手.2":"罚球出手"},
                inplace=True)
df_season.head()
print('df_season.head()',df_season.head())
#print('df_season.head()',df_season)

season = list(np.sort(df_season["赛季"].unique()))
season = season[2:] + season[:2]

df_season["win"] = df_season["果"].map({"胜": 1, "负": 0})
wining_rate = df_season.groupby(["赛季"])["win"].mean()[season].values

fig,ax = plt.subplots(figsize=(12,8))
fig.text(x=0.1, y=0.9, s='            常规赛的场均得分以及胜率        ',
         fontsize=32, weight='bold', color='white', backgroundcolor='#c5b783')
sns.barplot(x="赛季",y="得分",data=df_season,order=season,ci=None,color="#3c7f99")
plt.tick_params(labelsize=16,axis="both",direction="in")
plt.ylabel("场均得分",fontsize=14)
plt.xlabel("赛季",fontsize=14)
ax2=ax.twinx()
plt.scatter(x=season,y=wining_rate,color="r",marker='d')
plt.plot(season,wining_rate,color="r")
plt.tick_params(labelsize=16,axis="both",direction="in")
ax2.set_yticks([0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9])
plt.ylim(0.2,1)
plt.ylabel("胜率",fontsize=14)
plt.show()


#单场比赛各个得分段占比
#使用pie绘制饼图

interval = ["20分及以下","20-30","30-40","40-50","大于50"]
value = pd.cut(df_season["得分"],bins=[0,20,30,40,50,100],labels=interval).value_counts(normalize=True)[interval].values


pie = (
    Pie()
    .add(
        "",
        [list(z) for z in zip(interval, value)],
        center=["50%", "50%"],
       # radius=["50%","75%"]
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(title="单场比赛各个得分段占比",pos_left="center"),
        legend_opts=opts.LegendOpts(
                is_show=True
            )
    )
    .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {d}%")))

pie.render_notebook()



#柱形图
pattern = re.compile(r'[u4E00-u9FA5]+')
df_season["team_list"] = df_season["比赛"].str.findall(pattern).map(set)

def get_opp(x,num=0):
    period_dict = {0:"公牛",1:"奇才"}
    opp = (x-set([period_dict[num]])).pop()
    if opp == "人":
        return "76人"
    elif opp == "凯尔特":
        return "凯尔特人"
    elif opp == "超音速":
        return "雷霆"
    elif opp == "子弹":
        return "奇才"
    else:
        return opp
df_season.loc[~df_season["赛季"].isin(["01-02","02-03"]),"opp"] = df_season["team_list"].map(lambda x : get_opp(x,0))
df_season.loc[df_season["赛季"].isin(["01-02","02-03"]),"opp"] = df_season["team_list"].map(lambda x : get_opp(x,1))

fig, ax = plt.subplots(figsize=(12,8))
order = df_season.groupby("opp")["得分"].mean().sort_values(ascending=False).index
sns.barplot(y="opp",x = "得分",order=order,data=df_season,color='#3c7f99',ci=None)
plt.box(False)
fig.text(x=0.04, y=0.90, s='           对阵联盟各个球队的场均得分         ',
         fontsize=32, weight='bold', color='white', backgroundcolor='#c5b783')
plt.tick_params(axis='both', which='major', labelsize=16)
ax.xaxis.grid(which='both', linewidth=0.5, color='#3c7f99')
plt.xlabel('')
plt.ylabel('')
plt.show()

fig, ax = plt.subplots(figsize=(12,8))
order = df_season.groupby("opp")["win"].mean().sort_values(ascending=False).index
sns.barplot(y="opp",x = "win",order=order,data=df_season,color='#3c7f99',ci=None)
plt.box(False)
fig.text(x=0.04, y=0.90, s='           对阵联盟各个球队的胜率            ',
         fontsize=32, weight='bold', color='white', backgroundcolor='#c5b783')
plt.tick_params(axis='both', which='major', labelsize=16)
ax.xaxis.grid(which='both', linewidth=0.5, color='#3c7f99')
# plt.xticks([0.2,0.4,0.6,0.8,1.0])
plt.xlabel('')
plt.ylabel('')
plt.show()

pattern = re.compile("(d+)-(d+)")
df_season["diff"] = df_season["比赛"].str.findall(pattern).map(lambda x : np.abs(int(x[0][0])-int(x[0][1])))

fig, ax = plt.subplots(figsize=(12,8))
sns.swarmplot(x="果",y="diff",data=df_season)
fig.text(x=0.1, y=0.90, s='                输赢时的分差                ',
         fontsize=32, weight='bold', color='white', backgroundcolor='#3c7f99')
plt.tick_params(axis='both', which='major', labelsize=16)
plt.xlabel("分差",fontsize=16)
plt.ylabel("比赛结果",fontsize=16)
plt.show()


df_playoff = pd.read_excel("./playoff.xls")
df_playoff["win"] = df_playoff["果"].map({"胜":1,"负":0})

pattern = re.compile(r'[u4E00-u9FA5]+')
df_playoff["team_list"] = df_playoff["比赛"].str.findall(pattern).map(set)
df_playoff.loc[:,"opp"] = df_playoff["team_list"].map(lambda x : get_opp(x,0))

df_plot = df_playoff.groupby(["赛季","轮次","opp"])["win"].mean().reset_index()
# season_dict = dict(zip(df_plot["赛季"].unique(),[i for i in range(12)]))
# df_plot["season"] = df_plot["赛季"].map(season_dict)
# horizon = [0.11,0.18,0.24,0.30,0.37,0.43,0.50,0.56,0.63,0.69,0.76,0.82]
# vertical = [0.13,0.35,0.58,0.79]
# fig, ax = plt.subplots(figsize=(16, 8))
# fig.text(x=0.03, y=0.92, s='                         乔丹季后赛全景图                       ', fontsize=32,
#          weight='bold', color='white', backgroundcolor='#3c7f99')
# plt.scatter(df_plot["赛季"], df_plot["轮次"], alpha=0.35)
# plt.tick_params(axis='both', which='major', labelsize=16)
# plt.box(False)
# plt.yticks([1, 2, 3, 4], labels=["第一轮", "第二轮", "分区决赛", "总决赛"])
# plt.show()
# for point in range(len(df_plot)):
#     season = df_plot.iloc[point, 4]
#     round_ = df_plot.iloc[point, 1] - 1
#     team_name = df_plot.iloc[point, 2]
#     left, bottom, width, height = horizon[season], vertical[round_], 0.08, 0.08
#     ax2 = fig.add_axes([left, bottom, width, height])
#     img = Image.open("./picture/{team_name}.jpg".format(team_name=team_name))
#     ax2.imshow(img)
#     ax2.axis('off')  # 关掉坐标轴为 off

#
# pattern = re.compile("(d+)-(d+)")
# df_playoff["diff"] = df_playoff["比赛"].str.findall(pattern).map(lambda x : np.abs(int(x[0][0])-int(x[0][1])))
# color = df_playoff["果"].map({"胜":"#e60000","负":"#73e68c"})
#
# fig, ax = plt.subplots(figsize=(12, 8))
# fig.text(x=0.03, y=0.92, s='             季后赛各轮次的输赢分差           ', fontsize=32,
#          weight='bold', color='white', backgroundcolor='#3c7f99')
# plt.yticks([1,2,3,4],labels=["第一轮","第二轮","分区决赛","总决赛"])
# plt.scatter(df_playoff["diff"], df_playoff["轮次"], alpha=0.35,c=color,s=500)
# plt.scatter(df_playoff["diff"], df_playoff["轮次"], c=color)
# plt.tick_params(axis='both', which='both', length=0)
# plt.tick_params(axis='both', which='major', labelsize=16)
# ax.xaxis.grid(which='both', linewidth=0.75)
# #plt.xticks(np.arange(0,61,10), [str(i)+"k" for i in range(0,61,10)])
# plt.xlabel('分差', fontsize=18)
# plt.box(False)
# plt.show()
#seed_scale_plot()

season_score = df_season.groupby("赛季")["得分"].mean().values[2:]
playoff_score = df_playoff.groupby("赛季")["得分"].mean().values
index = df_playoff.groupby("赛季")["得分"].mean().index

fig, ax = plt.subplots(figsize=(12,8))
sns.barplot(x=index,y=playoff_score-season_score)
fig.text(x=0.06, y=0.90, s='            季后赛与常规赛场均得分差           ',
         fontsize=32, weight='bold', color='white', backgroundcolor='#3c7f99')
plt.tick_params(axis='both', which='major', labelsize=16)
plt.xlabel("赛季",fontsize=16)
plt.ylabel("场均分差",fontsize=16)
plt.box(False)




转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/950402.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号