2017-12-24 4 views
0

저는 matplotlib뿐 아니라 python을 처음 사용했습니다. matplotlib의 히스토그램을 사용하여 각 도시의 여행 데이터를 플로팅하려고합니다. 다음은 플롯하려고하는 샘플 데이터입니다.matplotlib의 히스토그램에 시간 간격 설정 및 제한 추가

데이터 :

 duration month hour day_of_week user_type 
0 15.433333  3 23 Thursday Subscriber 
1 3.300000  3 22 Thursday Subscriber 
2 2.066667  3 22 Thursday Subscriber 
3 19.683333  3 22 Thursday Subscriber 
4 10.933333  3 22 Thursday Subscriber 
5 19.000000  3 21 Thursday Subscriber 
6 6.966667  3 21 Thursday Subscriber 
7 17.033333  3 20 Thursday Subscriber 
8 6.116667  3 20 Thursday Subscriber 
9 6.316667  3 20 Thursday Subscriber 
10 11.300000  3 20 Thursday Subscriber 
11 8.300000  3 20 Thursday Subscriber 
12 8.283333  3 19 Thursday Subscriber 
13 36.033333  3 19 Thursday Subscriber 
14 5.833333  3 19 Thursday Subscriber 
15 5.350000  3 19 Thursday Subscriber 

코드 :

def get_durations_as_list(filename): 
     with open(filename, 'r') as f_in: 
      reader = csv.reader(f_in) 
      next(reader, None) 
      for row in reader: 
       if row[4] in ['Subscriber','Registered'] and float(row[0]) < 75: 
        subscribers.append(float(row[0])) 
       elif row[4] in ['Casual','Customer'] and float(row[0]) < 75: 
        customers.append(float(row[0])) 
      return subscribers,customers 

data_files = ['./data/Washington-2016-Summary.csv','./data/Chicago-2016-Summary.csv','./data/NYC-2016-Summary.csv',] 
for file in data_files: 
    city = file.split('-')[0].split('/')[-1] 
    subscribers,customers = get_durations_as_list(file) 

plt.hist(subscribers,range=[min(subscribers),max(subscribers)],bins=5) 
plt.title('Distribution of Subscriber Trip Durations for city {}'.format(city)) 
plt.xlabel('Duration (m)') 
plt.show() 

plt.hist(customers,range=[min(subscribers),max(subscribers)],bins=5) 
plt.title('Distribution of Customers Trip Durations for city {}'.format(city)) 
plt.xlabel('Duration (m)') 
plt.show() 

이제 질문은 넓은 5mins하는 시간 간격을 설정하는 방법과보다 작은 단지 여행을 플롯하는 방법입니다 75mins.

설명서를 읽었지만 복잡해 보입니다. 몇 stackoverflow 질문을 읽은 후 나는 빈이 시간 간격을 설정하는 데 사용되는 것을 발견했습니다. 제 가정은 정확합니까?

bins 인수는 빈 가장자리의 순서가 될 수 있습니다

답변

1

내가 여기에 그것을 밖으로 시도 수는 없지만 내 생각이다. 따라서 당신은 기간의 최소 및 최대 걸릴 수 있으며합니다 (numpy 라이브러리를 사용하여 여기에) 5의 스텝 크기의 순서를 만들 :

import numpy as np 
sequence = np.arange(min(dat['duration']), max(dat['duration']), 5) 

(어쩌면 당신은 바닥에 원하는을/정수의 최소값과 최대 값을 CEIL .) 코드는 pandas 라이브러리를 사용하여 데이터를 읽어야한다는 사실에 의존합니다. 필터는 pandas을 사용하여 쉽게 필터링 할 수 있습니다.

import pandas as pd 
dat = pd.read_csv('YOURFILE.csv') 
dat_filtered = dat[dat['duration'] < 75] 

해피 홀리데이.

0

예, 귀하의 가정은 대단히 정확합니다. bins 매개 변수를 시퀀스로 사용할 수 있습니다. 너의 경우에, 그것은 같을 것이다.

b = [ 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70] 

위의 목록을 생성하려면 numpy를 사용할 수 있습니다. 또한

bins = numpy.arange(0,75,5) 

, 하나 이하로 설정 가입자 및 고객 데이터를 사용할 수있는 것은

def plot_duration_type(filename): 
    city = filename.split('-')[0].split('/')[-1] 
    with open(filename, 'r') as f_in: 
     reader = csv.DictReader(f_in) 
     subscriber_duration = [] 
     customer_duration = [] 
     for row in reader: 
      if float(row['duration']) < 75 and row['user_type'] == 'Subscriber': 
       subscriber_duration.append(float(row['duration'])) 
      elif float(row['duration']) < 75 and row['user_type'] == 'Customer': 
       customer_duration.append(float(row['duration'])) 
    b = [ 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70] 
    plt.hist([subscriber_duration, customer_duration], bins=b, color=['orange', 'green'], 
       label=['Subscriber', 'Customer']) 
    title = "{} Distribution of Trip Durations".format(city) 
    plt.title(title) 
    plt.xlabel('Duration (m)') 
    plt.show() 

data_file = ['./data/Washington-2016-Summary.csv', './data/Chicago-2016-Summary.csv', './data/NYC-2016-Summary.csv'] 
for datafile in data_file: 
    print(plot_duration_type(datafile)) 
+0

이이 문제를 해결할 수 있으면 알려 주시기 바랍니다 기능을이다 –