matplotlib绘制甘特图之万能模板案例

简介: matplotlib绘制甘特图之万能模板案例

定义一个绘制甘特图的类

# -*- coding: utf-8 -*-
from datetime import datetime
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
import matplotlib.dates as mdates
import logging
from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei']
class Gantt(object):
    #颜色色标:参考http://colorbrewer2.org/
    RdYlGr = ['#d73027', '#f46d43', '#fdae61','#fee08b', '#ffffbf', '#d9ef8b','#a6d96a', '#66bd63', '#1a9850']
    POS_START = 1.0
    POS_STEP = 0.5
    def __init__(self, tasks):
        self._fig = plt.figure(figsize=(15,10))
        self._ax = self._fig.add_axes([0.1, 0.1, .75, .5])
        self.tasks = tasks[::-1]  # 倒序
    def _format_date(self, date_string):
        try:
            date = datetime.datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')  # 将日期字符串转换成datetime类型
        except ValueError as err:
            logging.error("String '{0}' can not be converted to datetime object: {1}"
                   .format(date_string, err))
            sys.exit(-1)
        mpl_date = mdates.date2num(date)  # 得到日期类型的时间戳
        return mpl_date
    def _plot_bars(self):
        i = 0
        for task in self.tasks:
            start = self._format_date(task['start'])  # 获取任务开始时间的时间戳
            end = self._format_date(task['end'])      # 获取任务结束时间的时间戳
            bottom = (i * Gantt.POS_STEP) + Gantt.POS_START
            width = end - start    # 柱子的宽度
            self._ax.barh(bottom, width, left=start, height=0.3,align='center', label=task['label'],color = Gantt.RdYlGr[i%len(Gantt.RdYlGr)])
            i += 1
    def _configure_yaxis(self):
        task_labels = [t['label'] for t in self.tasks]   # 所有的刻度文本标签
        pos = self._positions(len(task_labels))          # 素有的刻度值
        ylocs = self._ax.set_yticks(pos)                 # 设置y轴刻度线
        ylabels = self._ax.set_yticklabels(task_labels)  # 设置y轴刻度标签
        plt.setp(ylabels, size='medium')                 # 设置y轴刻度标签属性(中号字)
    def _configure_xaxis(self):
        self._ax.xaxis_date()     # 使用时间轴
        rule = mdates.rrulewrapper(mdates.WEEKLY, interval=1)   # 生成时间生成器(每周1个值,从周日开始)
        loc = mdates.RRuleLocator(rule)                         # 生成时间刻度
        formatter = mdates.DateFormatter("%m/%d")               # 生成时间格式
        self._ax.xaxis.set_major_locator(loc)          # 设置主刻度
        self._ax.xaxis.set_major_formatter(formatter)  # 设置主刻度标签格式
        xlabels = self._ax.get_xticklabels()           # 获取刻度标签对象
        plt.setp(xlabels, rotation=70, fontsize=10)    # 设置刻度标签对象的属性(30度旋转,字体大小10)
    def _configure_figure(self):
        self._configure_xaxis()
        self._configure_yaxis()
        self._ax.grid(True, axis='x',color='gray')
        self._set_legend()
        self._fig.autofmt_xdate()
    def _set_legend(self):
        font = font_manager.FontProperties(size='small')
        self._ax.legend(loc='upper right', prop=font)
    def _positions(self, count):
        end = count * Gantt.POS_STEP + Gantt.POS_START
        pos = np.arange(Gantt.POS_START, end, Gantt.POS_STEP)
        return pos
    def show(self):
        self._plot_bars()
        self._configure_figure()
        plt.show()

调用及数据格式

if __name__ == '__main__':
    TEST_DATA = (
                 { 'label': '项目调研', 'start':'2019-02-01 12:00:00', 'end': '2019-03-15 18:00:00'},
                 { 'label': '项目准备', 'start':'2019-02-15 09:00:00', 'end': '2019-04-09 12:00:00'},
                 { 'label': '制定方案', 'start':'2019-04-10 12:00:00', 'end': '2019-05-30 18:00:00'},
                 { 'label': '项目实施', 'start':'2019-05-01 09:00:00', 'end': '2019-08-31 13:00:00'},
                 { 'label': '项目培训', 'start':'2019-07-01 09:00:00', 'end': '2019-09-21 13:00:00'},
                 { 'label': '项目验收', 'start':'2019-09-22 09:00:00', 'end': '2019-10-22 13:00:00'},
                 { 'label': '项目竣工', 'start':'2019-10-23 09:00:00', 'end': '2019-11-23 13:00:00'},
                )
    gantt = Gantt(TEST_DATA)
    plt.xlabel('项目日期')
    plt.ylabel('项目进度')
    plt.title('项目进度甘特图')
    plt.figure(figsize=(10,10),dpi=150)
    gantt.show()

类似于展示的图形

image.png

相关文章
|
7月前
|
Python
使用Matplotlib创建不同类型图表的案例
使用Matplotlib创建不同类型图表的案例
39 2
|
6月前
|
Python
Python使用Matplotlib创建不同类型图表的案例
使用Matplotlib创建不同类型图表的案例
|
Python
matplotlib绘制箱形图之基本配置——万能模板案例(一)
matplotlib绘制箱形图之基本配置——万能模板案例
830 0
matplotlib绘制箱形图之基本配置——万能模板案例(一)
|
8天前
|
数据可视化 搜索推荐 数据处理
Matplotlib在数据科学中的应用与案例分析
【4月更文挑战第17天】本文探讨了Matplotlib在数据科学中的应用,强调其作为Python中最常用的可视化库,提供多种图表类型、高度可定制性、交互式功能及与其他库的集成。通过一个案例分析展示了如何使用Matplotlib绘制城市人口分布的条形图,并添加交互式元素以增强数据探索。掌握Matplotlib能提升数据科学家的可视化能力和效率。
|
4月前
|
Python
又再肝3天,整理了65个Matplotlib案例,这能不收藏?
又再肝3天,整理了65个Matplotlib案例,这能不收藏?
|
Python
matplotlib绘制雷达图之基本配置——万能模板案例
matplotlib绘制雷达图之基本配置——万能模板案例
741 0
matplotlib绘制雷达图之基本配置——万能模板案例
|
Python
matplotlib绘制火柴杆图之基本配置——万能模板案例
matplotlib绘制火柴杆图之基本配置——万能模板案例
165 0
matplotlib绘制火柴杆图之基本配置——万能模板案例
|
数据可视化 数据库 Python
matplotlib绘制箱形图之基本配置——万能模板案例(二)
matplotlib绘制箱形图之基本配置——万能模板案例
274 0
matplotlib绘制箱形图之基本配置——万能模板案例(二)
|
Python
matplotlib绘制树形图之基本配置——万能模板案例
matplotlib绘制树形图之基本配置——万能模板案例
266 0
matplotlib绘制树形图之基本配置——万能模板案例
|
Python
②matplotlib绘制直方图之基本配置——万能模板案例
matplotlib绘制直方图之基本配置——万能模板案例
179 0
②matplotlib绘制直方图之基本配置——万能模板案例