2016-09-09 3 views
6

나는이 작업을하기 위해 몇 시간 동안 노력했다. 나는 'python-gantt'패키지를 사용해 보았는데, 운이 없었다. 나는 또한 멋지게 시도했다. (어느 쪽이 아름다웠는지, 나는 그들의 민감한 데이터를 자신의 사이트에서 호스팅 할 수 없기 때문에 작동하지 않을 것이다).핫라인으로 간트 차트를 만드시겠습니까?

나의 출발점은 여기에서 코드입니다 : How to plot stacked event duration (Gantt Charts) using Python Pandas?

세 가지 요구 사항 :

  • 가 y 축이 아닌 숫자에 '이름'을 포함합니다.
  • 다른 이벤트가 여러 개있는 경우 모든 이벤트 기간을 한 줄에 입력하십시오. 이렇게하면 패턴을 쉽게 식별 할 수 있습니다. Lisa는 시각적으로 한 줄만 표시합니다.
  • 가능한 경우 해당 행 상단에 '이벤트'가 포함됩니다 (예 : 리사의 첫 번째 라인은 "고용"이라고 말할 것입니다. 내가 제안을 열려있어
코드는 더 많은 사람과 더 가능한 이벤트 유형을 수용하기 위해 동적해야합니다

...

는 시각화 : 나는 전반에 걸쳐 다양한 인력 이벤트의 기간을 표시 할 패턴 파악에 도움이됩니다.

from datetime import datetime 
import pandas as pd 
import matplotlib.pyplot as plt 
import matplotlib.dates as dt 

df = pd.DataFrame({'Name': ['Joe','Joe','Lisa','Lisa','Lisa','Alice'], 
        'Event': ['Hire','Term','Hire','Transfer','Term','Term'], 
        'Start_Date': ["2014-01-01","2014-02-01","2015-01-01","2015-02-01","2015-03-01","2016-01-01"], 
        'End_Date': ["2014-01-31","2014-03-15","2015-01-31","2015-02-28","2015-05-01","2016-09-01"] 
        }) 

df = df[['Name','Event','Start_Date','End_Date']] 

df.Start_Date = pd.to_datetime(df.Start_Date).astype(datetime) 
df.End_Date = pd.to_datetime(df.End_Date).astype(datetime) 

fig = plt.figure() 
ax = fig.add_subplot(111) 
ax = ax.xaxis_date() 
ax = plt.hlines(df.index, dt.date2num(df.Start_Date), dt.date2num(df.End_Date)) 

답변

6

이전에 같은 문제가 발생했습니다. 당신은 Plotly의 미학을 이해하는 것 같습니다. 다음은 matplotlib.pyplot.hlines 대신 matplotlib.pyplot.broken_barh을 사용하는 코드의 일부입니다.

from collections import defaultdict 
from datetime import datetime 
from datetime import date 
import pandas as pd 
import matplotlib.dates as mdates 
import matplotlib.patches as mpatches 
import matplotlib.pyplot as plt 

df = pd.DataFrame({ 
    'Name': ['Joe', 'Joe', 'Lisa', 'Lisa', 'Lisa', 'Alice'], 
    'Event': ['Hire', 'Term', 'Hire', 'Transfer', 'Term', 'Term'], 
    'Start_Date': ['2014-01-01', '2014-02-01', '2015-01-01', '2015-02-01', '2015-03-01', '2016-01-01'], 
    'End_Date': ['2014-01-31', '2014-03-15', '2015-01-31', '2015-02-28', '2015-05-01', '2016-09-01'] 
}) 

df = df[['Name', 'Event', 'Start_Date', 'End_Date']] 

df.Start_Date = pd.to_datetime(df.Start_Date).astype(datetime) 
df.End_Date = pd.to_datetime(df.End_Date).astype(datetime) 

names = df.Name.unique() 
nb_names = len(names) 

fig = plt.figure() 
ax = fig.add_subplot(111) 

bar_width = 0.8 
default_color = 'blue' 
colors_dict = defaultdict(lambda: default_color, Hire='green', Term='red', Transfer='orange') 

# Plot the events 
for index, name in enumerate(names): 
    mask = df.Name == name 
    start_dates = mdates.date2num(df.loc[mask].Start_Date) 
    end_dates = mdates.date2num(df.loc[mask].End_Date) 
    durations = end_dates - start_dates 
    xranges = zip(start_dates, durations) 
    ymin = index - bar_width/2.0 
    ywidth = bar_width 
    yrange = (ymin, ywidth) 
    facecolors = [colors_dict[event] for event in df.loc[mask].Event] 
    ax.broken_barh(xranges, yrange, facecolors=facecolors, alpha=1.0) 
    # you can set alpha to 0.6 to check if there are some overlaps 

# Shrink the x-axis 
box = ax.get_position() 
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) 

# Add the legend 
patches = [mpatches.Patch(color=color, label=key) for (key, color) in colors_dict.items()] 
patches = patches + [mpatches.Patch(color=default_color, label='Other')] 
plt.legend(handles=patches, bbox_to_anchor=(1, 0.5), loc='center left') 

# Format the x-ticks 
ax.xaxis.set_major_locator(mdates.YearLocator()) 
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y')) 
ax.xaxis.set_minor_locator(mdates.MonthLocator()) 

# Format the y-ticks 
ax.set_yticks(range(nb_names)) 
ax.set_yticklabels(names) 

# Set the limits 
date_min = date(df.Start_Date.min().year, 1, 1) 
date_max = date(df.End_Date.max().year + 1, 1, 1) 
ax.set_xlim(date_min, date_max) 

# Format the coords message box 
ax.format_xdata = mdates.DateFormatter('%Y-%m-%d') 

# Set the title 
ax.set_title('Gantt Chart') 

plt.show() 

Gantt Chart with broken_barh

은 내가 당신을 도울 바랍니다.

관련 문제