matplotlib绘制甘特图之万能模板案例
【摘要】
定义一个绘制甘特图的类
# -*- coding: utf-8 -*- from datetime import datetimeimport sysimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.font_manager as font_manag...
定义一个绘制甘特图的类
-
# -*- 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()
类似于展示的图形
每文一语
挂掉了服务器
文章来源: wxw-123.blog.csdn.net,作者:王小王-123,版权归原作者所有,如需转载,请联系作者。
原文链接:wxw-123.blog.csdn.net/article/details/124063816
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)