我的编程空间,编程开发者的网络收藏夹
学习永远不晚

Python+matplotlib实现折线图的美化

短信预约 -IT技能 免费直播动态提醒
省份

北京

  • 北京
  • 上海
  • 天津
  • 重庆
  • 河北
  • 山东
  • 辽宁
  • 黑龙江
  • 吉林
  • 甘肃
  • 青海
  • 河南
  • 江苏
  • 湖北
  • 湖南
  • 江西
  • 浙江
  • 广东
  • 云南
  • 福建
  • 海南
  • 山西
  • 四川
  • 陕西
  • 贵州
  • 安徽
  • 广西
  • 内蒙
  • 西藏
  • 新疆
  • 宁夏
  • 兵团
手机号立即预约

请填写图片验证码后获取短信验证码

看不清楚,换张图片

免费获取短信验证码

Python+matplotlib实现折线图的美化

大家好,今天分享一个非常有趣的 Python 教程,如何美化一个 matplotlib 折线图,喜欢记得收藏、关注、点赞。

1. 导入包

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.gridspec as gridspec

2. 获得数据

file_id = '1yM_F93NY4QkxjlKL3GzdcCQEnBiA2ltB'
url = f'https://drive.google.com/uc?id={file_id}'
df = pd.read_csv(url, index_col=0)
df

数据长得是这样的:

3. 对数据做一些预处理

按照需要,对数据再做一些预处理,代码及效果如下:

home_df = df.copy()
home_df = home_df.melt(id_vars = ["date", "home_team_name", "away_team_name"])
home_df["venue"] = "H"
home_df.rename(columns = {"home_team_name":"team", "away_team_name":"opponent"}, inplace = True)
home_df.replace({"variable":{"home_team_xG":"xG_for", "away_team_xG":"xG_ag"}}, inplace = True)
away_df = df.copy()
away_df = away_df.melt(id_vars = ["date", "away_team_name", "home_team_name"])
away_df["venue"] = "A"
away_df.rename(columns = {"away_team_name":"team", "home_team_name":"opponent"}, inplace = True)
away_df.replace({"variable":{"away_team_xG":"xG_for", "home_team_xG":"xG_ag"}}, inplace = True)
df = pd.concat([home_df, away_df]).reset_index(drop = True)
df

4. 画图

# ---- Filter the data

Y_for = df[(df["team"] == "Lazio") & (df["variable"] == "xG_for")]["value"].reset_index(drop = True)
Y_ag = df[(df["team"] == "Lazio") & (df["variable"] == "xG_ag")]["value"].reset_index(drop = True)
X_ = pd.Series(range(len(Y_for)))

# ---- Compute rolling average

Y_for = Y_for.rolling(window = 5, min_periods = 0).mean() # min_periods is for partial avg.
Y_ag = Y_ag.rolling(window = 5, min_periods = 0).mean()
fig, ax = plt.subplots(figsize = (7,3), dpi = 200)

ax.plot(X_, Y_for)
ax.plot(X_, Y_ag)

使用matplotlib倒是可以快速把图画好了,但是太丑了。接下来进行优化。

4.1 优化:添加点

这里为每一个数据添加点

fig, ax = plt.subplots(figsize = (7,3), dpi = 200)

# --- Remove spines and add gridlines

ax.spines["left"].set_visible(False)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)

ax.grid(ls = "--", lw = 0.5, color = "#4E616C")

# --- The data

ax.plot(X_, Y_for, marker = "o")
ax.plot(X_, Y_ag, marker = "o")

4.2 优化:设置刻度

fig, ax = plt.subplots(figsize = (7,3), dpi = 200)

# --- Remove spines and add gridlines

ax.spines["left"].set_visible(False)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)

ax.grid(ls = "--", lw = 0.25, color = "#4E616C")

# --- The data

ax.plot(X_, Y_for, marker = "o", mfc = "white", ms = 5)
ax.plot(X_, Y_ag, marker = "o", mfc = "white", ms = 5)

# --- Adjust tickers and spine to match the style of our grid

ax.xaxis.set_major_locator(ticker.MultipleLocator(2)) # ticker every 2 matchdays
xticks_ = ax.xaxis.set_ticklabels([x - 1 for x in range(0, len(X_) + 3, 2)])
# This last line outputs
# [-1, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35]
# and we mark the tickers every two positions.

ax.xaxis.set_tick_params(length = 2, color = "#4E616C", labelcolor = "#4E616C", labelsize = 6)
ax.yaxis.set_tick_params(length = 2, color = "#4E616C", labelcolor = "#4E616C", labelsize = 6)

ax.spines["bottom"].set_edgecolor("#4E616C")

4.3 优化:设置填充

fig, ax = plt.subplots(figsize = (7,3), dpi = 200)

# --- Remove spines and add gridlines

ax.spines["left"].set_visible(False)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)

ax.grid(ls = "--", lw = 0.25, color = "#4E616C")

# --- The data

ax.plot(X_, Y_for, marker = "o", mfc = "white", ms = 5)
ax.plot(X_, Y_ag, marker = "o", mfc = "white", ms = 5)

# --- Fill between

ax.fill_between(x = X_, y1 = Y_for, y2 = Y_ag, alpha = 0.5)

# --- Adjust tickers and spine to match the style of our grid

ax.xaxis.set_major_locator(ticker.MultipleLocator(2)) # ticker every 2 matchdays
xticks_ = ax.xaxis.set_ticklabels([x - 1 for x in range(0, len(X_) + 3, 2)])

ax.xaxis.set_tick_params(length = 2, color = "#4E616C", labelcolor = "#4E616C", labelsize = 6)
ax.yaxis.set_tick_params(length = 2, color = "#4E616C", labelcolor = "#4E616C", labelsize = 6)

ax.spines["bottom"].set_edgecolor("#4E616C")

4.4 优化:设置填充颜色

1.当橙色线更高时,希望填充为橙色。但是上面的还无法满足,这里再优化一下.

fig, ax = plt.subplots(figsize = (7,3), dpi = 200)

# --- Remove spines and add gridlines

ax.spines["left"].set_visible(False)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)

ax.grid(ls = "--", lw = 0.25, color = "#4E616C")

# --- The data

ax.plot(X_, Y_for, marker = "o", mfc = "white", ms = 5)
ax.plot(X_, Y_ag, marker = "o", mfc = "white", ms = 5)

# --- Fill between

# Identify points where Y_for > Y_ag

pos_for = (Y_for > Y_ag)
ax.fill_between(x = X_[pos_for], y1 = Y_for[pos_for], y2 = Y_ag[pos_for], alpha = 0.5)

pos_ag = (Y_for <= Y_ag)
ax.fill_between(x = X_[pos_ag], y1 = Y_for[pos_ag], y2 = Y_ag[pos_ag], alpha = 0.5)

# --- Adjust tickers and spine to match the style of our grid

ax.xaxis.set_major_locator(ticker.MultipleLocator(2)) # ticker every 2 matchdays
xticks_ = ax.xaxis.set_ticklabels([x - 1 for x in range(0, len(X_) + 3, 2)])

ax.xaxis.set_tick_params(length = 2, color = "#4E616C", labelcolor = "#4E616C", labelsize = 6)
ax.yaxis.set_tick_params(length = 2, color = "#4E616C", labelcolor = "#4E616C", labelsize = 6)

ax.spines["bottom"].set_edgecolor("#4E616C")

上面的图出现异常,再修改一下:

X_aux = X_.copy()
X_aux.index = X_aux.index * 10 # 9 aux points in between each match
last_idx = X_aux.index[-1] + 1
X_aux = X_aux.reindex(range(last_idx))
X_aux = X_aux.interpolate()


# --- Aux series for the xG created (Y_for)
Y_for_aux = Y_for.copy()
Y_for_aux.index = Y_for_aux.index * 10
last_idx = Y_for_aux.index[-1] + 1
Y_for_aux = Y_for_aux.reindex(range(last_idx))
Y_for_aux = Y_for_aux.interpolate()

# --- Aux series for the xG conceded (Y_ag)
Y_ag_aux = Y_ag.copy()
Y_ag_aux.index = Y_ag_aux.index * 10
last_idx = Y_ag_aux.index[-1] + 1
Y_ag_aux = Y_ag_aux.reindex(range(last_idx))
Y_ag_aux = Y_ag_aux.interpolate()



fig, ax = plt.subplots(figsize = (7,3), dpi = 200)

# --- Remove spines and add gridlines

ax.spines["left"].set_visible(False)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)

ax.grid(ls = "--", lw = 0.25, color = "#4E616C")

# --- The data

for_ = ax.plot(X_, Y_for, marker = "o", mfc = "white", ms = 5)
ag_ = ax.plot(X_, Y_ag, marker = "o", mfc = "white", ms = 5)

# --- Fill between

for index in range(len(X_aux) - 1):
    # Choose color based on which line's on top
    if Y_for_aux.iloc[index + 1] > Y_ag_aux.iloc[index + 1]:
        color = for_[0].get_color()
    else:
        color = ag_[0].get_color()
    
    # Fill between the current point and the next point in pur extended series.
    ax.fill_between([X_aux[index], X_aux[index+1]], 
                    [Y_for_aux.iloc[index], Y_for_aux.iloc[index+1]], 
                    [Y_ag_aux.iloc[index], Y_ag_aux.iloc[index+1]], 
                    color=color, zorder = 2, alpha = 0.2, ec = None)

# --- Adjust tickers and spine to match the style of our grid

ax.xaxis.set_major_locator(ticker.MultipleLocator(2)) # ticker every 2 matchdays
xticks_ = ax.xaxis.set_ticklabels([x - 1 for x in range(0, len(X_) + 3, 2)])

ax.xaxis.set_tick_params(length = 2, color = "#4E616C", labelcolor = "#4E616C", labelsize = 6)
ax.yaxis.set_tick_params(length = 2, color = "#4E616C", labelcolor = "#4E616C", labelsize = 6)

ax.spines["bottom"].set_edgecolor("#4E616C")

5. 把功能打包成函数

上面的样子都还不错啦,接下来把这些东西都打包成一个函数。方便后面直接出图。

def plot_xG_rolling(team, ax, window = 5, color_for = "blue", color_ag = "orange", data = df):
  '''
  This function creates a rolling average xG plot for a given team and rolling
  window.

  team (str): The team's name
  ax (obj): a Matplotlib axes.
  window (int): The number of periods for our rolling average.
  color_for (str): A hex color code for xG created.
  color_af (str): A hex color code for xG conceded.
  data (DataFrame): our df with the xG data.
  '''

  # -- Prepping the data
  home_df = data.copy()
  home_df = home_df.melt(id_vars = ["date", "home_team_name", "away_team_name"])
  home_df["venue"] = "H"
  home_df.rename(columns = {"home_team_name":"team", "away_team_name":"opponent"}, inplace = True)
  home_df.replace({"variable":{"home_team_xG":"xG_for", "away_team_xG":"xG_ag"}}, inplace = True)

  away_df = data.copy()
  away_df = away_df.melt(id_vars = ["date", "away_team_name", "home_team_name"])
  away_df["venue"] = "A"
  away_df.rename(columns = {"away_team_name":"team", "home_team_name":"opponent"}, inplace = True)
  away_df.replace({"variable":{"away_team_xG":"xG_for", "home_team_xG":"xG_ag"}}, inplace = True)

  df = pd.concat([home_df, away_df]).reset_index(drop = True)

  # ---- Filter the data

  Y_for = df[(df["team"] == team) & (df["variable"] == "xG_for")]["value"].reset_index(drop = True)
  Y_ag = df[(df["team"] == team) & (df["variable"] == "xG_ag")]["value"].reset_index(drop = True)
  X_ = pd.Series(range(len(Y_for)))

  if Y_for.shape[0] == 0:
    raise ValueError(f"Team {team} is not present in the DataFrame")

  # ---- Compute rolling average

  Y_for = Y_for.rolling(window = 5, min_periods = 0).mean() # min_periods is for partial avg.
  Y_ag = Y_ag.rolling(window = 5, min_periods = 0).mean()

  # ---- Create auxiliary series for filling between curves

  X_aux = X_.copy()
  X_aux.index = X_aux.index * 10 # 9 aux points in between each match
  last_idx = X_aux.index[-1] + 1
  X_aux = X_aux.reindex(range(last_idx))
  X_aux = X_aux.interpolate()

  # --- Aux series for the xG created (Y_for)
  Y_for_aux = Y_for.copy()
  Y_for_aux.index = Y_for_aux.index * 10
  last_idx = Y_for_aux.index[-1] + 1
  Y_for_aux = Y_for_aux.reindex(range(last_idx))
  Y_for_aux = Y_for_aux.interpolate()

  # --- Aux series for the xG conceded (Y_ag)
  Y_ag_aux = Y_ag.copy()
  Y_ag_aux.index = Y_ag_aux.index * 10
  last_idx = Y_ag_aux.index[-1] + 1
  Y_ag_aux = Y_ag_aux.reindex(range(last_idx))
  Y_ag_aux = Y_ag_aux.interpolate()

  # --- Plotting our data

  # --- Remove spines and add gridlines

  ax.spines["left"].set_visible(False)
  ax.spines["top"].set_visible(False)
  ax.spines["right"].set_visible(False)

  ax.grid(ls = "--", lw = 0.25, color = "#4E616C")

  # --- The data

  for_ = ax.plot(X_, Y_for, marker = "o", mfc = "white", ms = 4, color = color_for)
  ag_ = ax.plot(X_, Y_ag, marker = "o", mfc = "white", ms = 4, color = color_ag)

  # --- Fill between

  for index in range(len(X_aux) - 1):
      # Choose color based on which line's on top
      if Y_for_aux.iloc[index + 1] > Y_ag_aux.iloc[index + 1]:
          color = for_[0].get_color()
      else:
          color = ag_[0].get_color()
      
      # Fill between the current point and the next point in pur extended series.
      ax.fill_between([X_aux[index], X_aux[index+1]], 
                      [Y_for_aux.iloc[index], Y_for_aux.iloc[index+1]], 
                      [Y_ag_aux.iloc[index], Y_ag_aux.iloc[index+1]], 
                      color=color, zorder = 2, alpha = 0.2, ec = None)
      

  # --- Ensure minimum value of Y-axis is zero
  ax.set_ylim(0)

  # --- Adjust tickers and spine to match the style of our grid

  ax.xaxis.set_major_locator(ticker.MultipleLocator(2)) # ticker every 2 matchdays
  xticks_ = ax.xaxis.set_ticklabels([x - 1 for x in range(0, len(X_) + 3, 2)])

  ax.xaxis.set_tick_params(length = 2, color = "#4E616C", labelcolor = "#4E616C", labelsize = 6)
  ax.yaxis.set_tick_params(length = 2, color = "#4E616C", labelcolor = "#4E616C", labelsize = 6)

  ax.spines["bottom"].set_edgecolor("#4E616C")

  # --- Legend and team name

  Y_for_last = Y_for.iloc[-1]
  Y_ag_last = Y_ag.iloc[-1]

  # -- Add the team's name
  team_ = ax.text(
            x = 0, y = ax.get_ylim()[1] + ax.get_ylim()[1]/20,
            s = f'{team}',
            color = "#4E616C",
            va = 'center',
            ha = 'left',
            size = 7
          )
  
  # -- Add the xG created label
  for_label_ = ax.text(
            x = X_.iloc[-1] + 0.75, y = Y_for_last,
            s = f'{Y_for_last:,.1f} xGF',
            color = color_for,
            va = 'center',
            ha = 'left',
            size = 6.5
          )

  # -- Add the xG conceded label
  ag_label_ = ax.text(
            x = X_.iloc[-1] + 0.75, y = Y_ag_last,
            s = f'{Y_ag_last:,.1f} xGA',
            color = color_ag,
            va = 'center',
            ha = 'left',
            size = 6.5
          )

6.测试函数

file_id = '1yM_F93NY4QkxjlKL3GzdcCQEnBiA2ltB'
url = f'https://drive.google.com/uc?id={file_id}'
df = pd.read_csv(url, index_col=0)
fig = plt.figure(figsize=(5, 2), dpi = 200)
ax = plt.subplot(111)

plot_xG_rolling("Sassuolo", ax, color_for = "#00A752", color_ag = "black", data = df)

plt.tight_layout()

再设置更加丰富的颜色:

fig = plt.figure(figsize=(5, 8), dpi = 200, facecolor = "#EFE9E6")

ax1 = plt.subplot(411, facecolor = "#EFE9E6")
ax2 = plt.subplot(412, facecolor = "#EFE9E6")
ax3 = plt.subplot(413, facecolor = "#EFE9E6")
ax4 = plt.subplot(414, facecolor = "#EFE9E6")

plot_xG_rolling("Sassuolo", ax1, color_for = "#00A752", color_ag = "black", data = df)
plot_xG_rolling("Lazio", ax2, color_for = "#87D8F7", color_ag = "#15366F", data = df)
plot_xG_rolling("Hellas Verona", ax3, color_for = "#153aab", color_ag = "#fdcf41", data = df)
plot_xG_rolling("Empoli", ax4, color_for = "#00579C", color_ag = "black", data = df)

plt.tight_layout()

最后

其实本文主要是对两个折线图做了一系列的优化和改进而已,主要是强调细节部分。

涉及到的matplotlib的知识,也主要是在ticks、背景颜色、fill_between部分。

以上就是Python+matplotlib实现折线图的美化的详细内容,更多关于Python matplotlib折线图的资料请关注编程网其它相关文章!

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

Python+matplotlib实现折线图的美化

下载Word文档到电脑,方便收藏和打印~

下载Word文档

猜你喜欢

怎么用Python matplotlib实现折线图

这篇文章主要介绍“怎么用Python matplotlib实现折线图”,在日常操作中,相信很多人在怎么用Python matplotlib实现折线图问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么用Pyth
2023-06-29

Python+Matplotlib实现绘制三维折线图

立体图视觉上层次分明色彩鲜艳,具有很强的视觉冲击力,让观看的人驻景时间长,留下深刻的印象。今天我们就通过这篇文章来了解如何用python中的matplotlib库绘制漂亮的三维折线图吧
2023-03-21

如何使用python的matplotlib绘制折线图

这篇文章主要介绍“如何使用python的matplotlib绘制折线图”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“如何使用python的matplotlib绘制折线图”文章能帮助大家解决问题。pl
2023-07-02

Python matplotlib之折线图的各种样式与画法总结

matplotlib是Python中的一个第三方库,主要用于开发2D图表,以渐进式、交互式的方式实现数据可视化,可以更直观的呈现数据,使数据更具说服力,下面这篇文章主要给大家介绍了关于Python matplotlib之折线图的各种样式与画法的相关资料,需要的朋友可以参考下
2022-12-22

QtQChart实现折线图的绘制

QChart是常用的图表,这篇文章主要为大家详细介绍了Qt如何利用QChart实现折线图的绘制,文中的示例代码讲解详细,感兴趣的可以了解一下
2023-05-17

Python可视化的折线图是怎样的

本篇文章给大家分享的是有关Python可视化的折线图是怎样的,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。摘要: 利用matplotlib绘制横轴为日期格式的折线图时,存在不少
2023-06-02

Python+matplotlib怎么实现绘制等高线图

本篇内容主要讲解“Python+matplotlib怎么实现绘制等高线图”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Python+matplotlib怎么实现绘制等高线图”吧!1. 等高线图概
2023-06-21

WPF+ASP.NETSignalR实现动态折线图的绘制

这篇文章将以一个简单的动态折线图示例,简述如何通过ASP.NETSignalR实现后台通知功能,文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下
2023-01-03

编程热搜

  • Python 学习之路 - Python
    一、安装Python34Windows在Python官网(https://www.python.org/downloads/)下载安装包并安装。Python的默认安装路径是:C:\Python34配置环境变量:【右键计算机】--》【属性】-
    Python 学习之路 - Python
  • chatgpt的中文全称是什么
    chatgpt的中文全称是生成型预训练变换模型。ChatGPT是什么ChatGPT是美国人工智能研究实验室OpenAI开发的一种全新聊天机器人模型,它能够通过学习和理解人类的语言来进行对话,还能根据聊天的上下文进行互动,并协助人类完成一系列
    chatgpt的中文全称是什么
  • C/C++中extern函数使用详解
  • C/C++可变参数的使用
    可变参数的使用方法远远不止以下几种,不过在C,C++中使用可变参数时要小心,在使用printf()等函数时传入的参数个数一定不能比前面的格式化字符串中的’%’符号个数少,否则会产生访问越界,运气不好的话还会导致程序崩溃
    C/C++可变参数的使用
  • css样式文件该放在哪里
  • php中数组下标必须是连续的吗
  • Python 3 教程
    Python 3 教程 Python 的 3.0 版本,常被称为 Python 3000,或简称 Py3k。相对于 Python 的早期版本,这是一个较大的升级。为了不带入过多的累赘,Python 3.0 在设计的时候没有考虑向下兼容。 Python
    Python 3 教程
  • Python pip包管理
    一、前言    在Python中, 安装第三方模块是通过 setuptools 这个工具完成的。 Python有两个封装了 setuptools的包管理工具: easy_install  和  pip , 目前官方推荐使用 pip。    
    Python pip包管理
  • ubuntu如何重新编译内核
  • 改善Java代码之慎用java动态编译

目录