logo
down
shadow

Is there a way to create gantt charts in python?


Is there a way to create gantt charts in python?

By : Antwan Ogwan
Date : October 25 2020, 07:10 AM
Hope that helps How about altair-viz (docs)?
code :
import pandas as pd
import numpy as np
import altair as alt
# alt.renderers.enable('notebook') # if in jupyter

df = pd.read_csv("tasks.csv")
df["Start date"] = pd.to_datetime(df["Start date"])
df["End date"] = pd.to_datetime(df["End date"])

chart = alt.Chart(df.drop("Resources", 1)).mark_bar().encode(
    x='Start date',
    x2='End date',
    y=alt.Y('Task Name', 
            sort=list(df.sort_values(["End date", "Start date"])
                                    ["Task Name"])), # Custom sorting
)

chart
-  -----------------------------------  -------------------  -------------------  ---------------------------------
0  Data type handling / Auto Inference  2019-07-01 00:00:00  2019-07-31 00:00:00  Backend
1  Sklearn & other models               2019-07-01 00:00:00  2019-07-31 00:00:00  Models
2  Maps / Geoplotting                   2019-07-01 00:00:00  2019-07-31 00:00:00  Backend, Graphical User Interface
3  Optimize Dockerfile                  2019-07-01 00:00:00  2019-07-31 00:00:00  CI/CD
4  Chapter 2: Compare competitors       2019-07-08 00:00:00  2019-10-21 00:00:00  Writing
-  -----------------------------------  -------------------  -------------------  ---------------------------------
# Use the progress to find how much of the bars should be filled
# (i.e. another end date)
df["progress date"] =  (df["End date"] - df["Start date"]) * df["Progress %"] / 100 + df["Start date"]

# Concatenate the two 
newdf = np.concatenate([df[["Task Name", "Start date", "End date", "Progress %"]].values,  
                        df[["Task Name", "Start date", "progress date", "Progress %"]].values])
newdf = pd.DataFrame(newdf, columns=["Task Name", "Start date", "End date", "Progress %"])

# Reconvert back to datetime
newdf["Start date"] = pd.to_datetime(newdf["Start date"])
newdf["End date"] = pd.to_datetime(newdf["End date"])

# This is the indicator variable (duration vs progress) where the grouping takes place
newdf["progress_"] = np.concatenate([np.ones(len(newdf)//2), np.zeros(len(newdf)//2), ])

# color for first half, color for second half
range_ = ['#1f77b4', '#5fa0d4',]

# The stacked bar chart will be our "gantt with progress"
chart = alt.Chart(newdf).mark_bar().encode(
    x=alt.X('Start date', stack=None),
    x2='End date',
    y=alt.Y('Task Name', sort=list(df.sort_values(["End date",
                                                      "Start date"])["Task Name"])*2),
    color=alt.Color('progress_', scale=alt.Scale(range=range_), legend=None)
) 

# Create appropriate labels
newdf["text%"] = newdf["Progress %"].astype(str) + " %"

# And now add those as text in the graph
text = alt.Chart(newdf).mark_text(align='left', baseline='middle', dx=5, color="white",  fontWeight="bold").encode(
    y=alt.Y('Task Name', sort=list(df.sort_values(["End date",
                                                      "Start date"])["Task Name"])*2),
    x=alt.X('Start date'),
    text='text%',
)

# Plot the graph
alt.layer(chart, text)


Share : facebook icon twitter icon
Gantt Charts

Gantt Charts


By : john clarke
Date : March 29 2020, 07:55 AM
hope this fix your issue Make sure you set the CellLayout.BackgroundUse=true. If you don't the Background color is ignored.
And since you use ASP.NET the cellLayouts will generate a css, so you must add the new cloned CellLayouts to the collection on CellLayouts:
Python: module for plotting Gantt charts

Python: module for plotting Gantt charts


By : Dylan 'Win' Griffith
Date : March 29 2020, 07:55 AM
should help you out ChartDirector is pretty good at generating advanced charts of all kinds. It has decent python bindings, but it's, unfortunately, not native python or open source in general.
There are actually some Gantt chart examples/screenshots. The code also includes python demo's for building gantt charts.
How to plot stacked event duration (Gantt Charts) using Python Pandas?

How to plot stacked event duration (Gantt Charts) using Python Pandas?


By : Andrea Hurr
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , I think you are trying to create a gantt plot. This suggests using hlines:
code :
from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dt

df = pd.read_csv('data.csv')
df.amin = pd.to_datetime(df.amin).astype(datetime)
df.amax = pd.to_datetime(df.amax).astype(datetime)

fig = plt.figure()
ax = fig.add_subplot(111)
ax = ax.xaxis_date()
ax = plt.hlines(df.index, dt.date2num(df.amin), dt.date2num(df.amax))
Tableau Gantt Waterfall Charts Bridge charts

Tableau Gantt Waterfall Charts Bridge charts


By : Serge
Date : March 29 2020, 07:55 AM
To fix this issue http://image.slidesharecdn.com/howtocreateatableauwaterfallchart-120307010026-phpapp02/95/how-to-create-a-tableau-waterfall-chart-9-638.jpg?cb=1376818931
You could do a dual axis to get this, with the ending total value on the second axis... *might need an LOD calc to exclude the slicing dimension for the bar on the one axis.
Google charts, how to add custom points on Gantt Charts?

Google charts, how to add custom points on Gantt Charts?


By : Barry Hinrichs
Date : March 29 2020, 07:55 AM
I hope this helps you . there are no standard options to add custom points,
but we can manually add on the chart's 'ready' event.
code :
addMarker('Find sources', new Date(2019, 0, 3));
addMarker('Outline paper', new Date(2019, 0, 5, 12));
addMarker('Write paper', new Date(2019, 0, 8));
google.charts.load('current', {
  packages:['gantt']
}).then(function () {
  var container = document.getElementById('gantt');
  var chart = new google.visualization.Gantt(container);

  var dataTable = new google.visualization.DataTable();
  dataTable.addColumn('string', 'Task ID');
  dataTable.addColumn('string', 'Task Name');
  dataTable.addColumn('string', 'Resource');
  dataTable.addColumn('date', 'Start Date');
  dataTable.addColumn('date', 'End Date');
  dataTable.addColumn('number', 'Duration');
  dataTable.addColumn('number', 'Percent Complete');
  dataTable.addColumn('string', 'Dependencies');
  dataTable.addRows([
    ['Research', 'Find sources', null, new Date(2019, 0, 1), new Date(2019, 0, 5), null,  100,  null],
    ['Write', 'Write paper', 'write', null, new Date(2019, 0, 9), daysToMilliseconds(3), 25, 'Research,Outline'],
    ['Cite', 'Create bibliography', 'write', null, new Date(2019, 0, 7), daysToMilliseconds(1), 20, 'Research'],
    ['Complete', 'Hand in paper', 'complete', null, new Date(2019, 0, 10), daysToMilliseconds(1), 0, 'Cite,Write'],
    ['Outline', 'Outline paper', 'write', null, new Date(2019, 0, 6), daysToMilliseconds(1), 100, 'Research']
  ]);

  var dateRangeStart = dataTable.getColumnRange(3);
  var dateRangeEnd = dataTable.getColumnRange(4);
  var formatDate = new google.visualization.DateFormat({
    pattern: 'MM/dd/yyyy'
  });
  var rowHeight = 45;

  var options = {
    height: ((dataTable.getNumberOfRows() * rowHeight) + rowHeight),
    gantt: {
      criticalPathEnabled: true,
      criticalPathStyle: {
        stroke: '#e64a19',
        strokeWidth: 5
      }
    }
  };

  function daysToMilliseconds(days) {
    return days * 24 * 60 * 60 * 1000;
  }

  function drawChart() {
    chart.draw(dataTable, options);
  }

  function addMarker(markerRow, markerDate) {
    var baseline;
    var baselineBounds;
    var chartElements;
    var marker;
    var markerSpan;
    var rowLabel;
    var svg;
    var svgNS;
    var gantt;
    var ganttUnit;
    var ganttWidth;
    var timespan;
    var xCoord;
    var yCoord;

    // initialize chart elements
    baseline = null;
    gantt = null;
    rowLabel = null;
    svg = null;
    svgNS = null;
    chartElements = container.getElementsByTagName('svg');
    if (chartElements.length > 0) {
      svg = chartElements[0];
      svgNS = svg.namespaceURI;
    }
    chartElements = container.getElementsByTagName('rect');
    if (chartElements.length > 0) {
      gantt = chartElements[0];
    }
    chartElements = container.getElementsByTagName('path');
    if (chartElements.length > 0) {
      Array.prototype.forEach.call(chartElements, function(path) {
        if ((baseline === null) && (path.getAttribute('fill') !== 'none')) {
          baseline = path;
        }
      });
    }
    chartElements = container.getElementsByTagName('text');
    if (chartElements.length > 0) {
      Array.prototype.forEach.call(chartElements, function(label) {
        if (label.textContent === markerRow) {
          rowLabel = label;
        }
      });
    }
    if ((svg === null) || (gantt === null) || (baseline === null) || (rowLabel === null) ||
        (markerDate.getTime() < dateRangeStart.min.getTime()) ||
        (markerDate.getTime() > dateRangeEnd.max.getTime())) {
      return;
    }

    // calculate placement
    ganttWidth = parseFloat(gantt.getAttribute('width'));
    baselineBounds = baseline.getBBox();
    timespan = dateRangeEnd.max.getTime() - dateRangeStart.min.getTime();
    ganttUnit = (ganttWidth - baselineBounds.x) / timespan;
    markerSpan = markerDate.getTime() - dateRangeStart.min.getTime();

    // add marker
    marker = document.createElementNS(svgNS, 'polygon');
    marker.setAttribute('fill', 'transparent');
    marker.setAttribute('stroke', '#ffeb3b');
    marker.setAttribute('stroke-width', '3');
    xCoord = (baselineBounds.x + (ganttUnit * markerSpan) - 4);
    yCoord = parseFloat(rowLabel.getAttribute('y'));
    marker.setAttribute('points', xCoord + ',' + (yCoord - 10) + ' ' + (xCoord - 5) + ',' + yCoord + ' ' + (xCoord + 5) + ',' + yCoord);
    svg.insertBefore(marker, rowLabel.parentNode);
  }

  google.visualization.events.addListener(chart, 'ready', function () {
    // add marker for current date
    addMarker('Find sources', new Date(2019, 0, 3));
    addMarker('Outline paper', new Date(2019, 0, 5, 12));
    addMarker('Write paper', new Date(2019, 0, 8));
  });

  window.addEventListener('resize', drawChart, false);
  drawChart();
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="gantt"></div>
Related Posts Related Posts :
  • Percent signs in windows path
  • How to add a random number to a subsection of a numpy array?
  • How to generate all the values of an iterable besides the last few?
  • Searching by both class and range in XPath
  • Python code execution in Perl interpreter
  • Best Way to Include Variable in Python3
  • Serialize the @property methods in a Python class
  • What is the most platform- and Python-version-independent way to make a fast loop for use in Python?
  • Good way to edit the previous defined class in ipython
  • Bounced email on Google App Engine
  • Search jpeg files using python
  • Dynamically create class attributes
  • python unichr problem
  • Python beginner, strange output problem
  • Python: Finding a value in 1 list and finding that corresponding index in another list
  • can't install mysqlclient on mac os x mojave
  • Error indicates flattened dimensions when loading pre-trained network
  • how to replace underlines with words?
  • Adding through iteration
  • Use OpenCV on deployed Flask app (Heroku)
  • How to skip interstitial in a django view if a user hits the back button?
  • Any Naive Bayesian Classifier in python?
  • Python 2.5.2: remove what found between two lines that contain two concrete strings
  • Python 2.5.2 script that add "The function starts here" to all the functions of the files of a directory
  • HttpResponseRedirect question
  • Python socket error on UDP data receive. (10054)
  • Encoding issues with cloud ml
  • numpy.where - Weird behaviour: new elements spawning from nowhere?
  • I can't move my player in pygame, can you figure why?
  • Weird error I receive from Tkinter in Python
  • Using a Zapier Custom Request Webhook with JSON Web Tokens
  • Keras: Use categorical_crossentropy without one-hot encoded array of targets
  • Does python's httplib.HTTPConnection block?
  • Do alternate python implementation version numbers imply that they provide the same syntax?
  • Searching for specific HTML string using Python
  • python sax error "junk after document element"
  • MySql: How to know if an entry is compressed or not
  • Return a list of imported Python modules used in a script?
  • Returning a list in this recursive coi function in python
  • Python2.6 Decimal to Octal
  • Appengine Apps Vs Google bot web crawler
  • Changing models in django results in broken database?
  • Global variable functions
  • Using lambda inside a function
  • How to open a file, replace some strings, and save updates to the same file?
  • How to move the beginning of an input to the and?
  • If else fill variable if empty list
  • Pandas: Find and print all floats in column
  • sqlite3.OperationalError: database is locked - non-threaded application
  • How to implement mib module in net-snmp with python?
  • Does Python/Scipy have a firls( ) replacement (i.e. a weighted, least squares, FIR filter design)?
  • sorl-thumbnail and file renaming
  • Python -- what is NOT in 2.7 that IS in 3.1? So many things have been back-ported, what is NOT?
  • How to make a Django model fields calculated at runtime?
  • Django - Threading in views without hanging the server
  • Python: Why is my POST requests not working?
  • Tried to add a value to a while condition, but it doesn't go back
  • How do I exit a while-true loop after 5 tries?
  • win python3 Multithreading
  • Compare 2 dictionaries in python
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk