2016-06-29 3 views
4

문제 :하기 matplotlib에서 여러 히스토그램을 플롯 할 때, 나는 이미지와 같은 다른플로팅 여러 히스토그램 - 색상 또는 사이드 바이 사이드 바

문제에서 플롯을 구별 할 수 없습니다 ** Problem ** 사소한 문제 : 왼쪽 라벨 'Count'가 부분적으로 이미지에서 벗어났습니다. 왜?

I는 3 개 가지 세트의 히스토그램을 플롯 할

설명. 각 집합은 0과 1을 가진 배열입니다. 각각의 히스토그램을 원해서 데이터 세트의 불균형을 감지 할 수 있습니다.

나는 그 (것)들을 따로 음모로 꾸몄다 그러나 나는 그 (것)들의 그래픽을 함께 원했다.

가로형 막대가있는 다른 그래픽을 사용하거나 3D로 플로팅하는 방법에 대해 봤지만 그래픽을 "읽거나"보는 것이 얼마나 쉬운 지 모르겠습니다. 그것을 이해하십시오.

는 지금, 내가 [기차] 플롯하려면, [확인]과 같은 그래픽의 각 측 [테스트] 바,이 같은 :

I want it like this

PS : 내 인터넷 검색 나에게 이해할 수있는 코드를 반환하지 않았습니다. 또한 누군가가 어떤 일을하고 있는지 확인하는 사람이 있다면 광기가입니다.

고마워요!

코드 : 해시 코드의 대답에 따라

def generate_histogram_from_array_of_labels(Y=[], labels=[], xLabel="Class/Label", yLabel="Count", title="Histogram of Trainset"): 
    plt.figure() 
    plt.clf() 

    colors = ["b", "r", "m", "w", "k", "g", "c", "y"] 

    information = [] 
    for index in xrange(0, len(Y)): 
     y = Y[index] 

     if index > len(colors): 
      color = colors[0] 
     else: 
      color = colors[index] 

     if labels is None: 
      label = "?" 
     else: 
      if index < len(labels): 
       label = labels[index] 
      else: 
       label = "?" 

     unique, counts = np.unique(y, return_counts=True) 
     unique_count = np.empty(shape=(unique.shape[0], 2), dtype=np.uint32) 

     for x in xrange(0, unique.shape[0]): 
      unique_count[x, 0] = unique[x] 
      unique_count[x, 1] = counts[x] 

     information.append(unique_count) 

     # the histogram of the data 
     n, bins, patches = plt.hist(y, unique.shape[0], normed=False, facecolor=color, alpha=0.75, range=[np.min(unique), np.max(unique) + 1], label=label) 

    xticks_pos = [0.5 * patch.get_width() + patch.get_xy()[0] for patch in patches] 

    plt.xticks(xticks_pos, unique) 

    plt.xlabel(xLabel) 
    plt.ylabel(yLabel) 
    plt.title(title) 
    plt.grid(True) 
    plt.legend() 
    # plt.show() 

    string_of_graphic_image = cStringIO.StringIO() 

    plt.savefig(string_of_graphic_image, format='png') 
    string_of_graphic_image.seek(0) 

    return base64.b64encode(string_of_graphic_image.read()), information 

편집

이 새로운 코드 :

012 :

def generate_histogram_from_array_of_labels(Y=[], labels=[], xLabel="Class/Label", yLabel="Count", title="Histogram of Trainset"): 
    plt.figure() 
    plt.clf() 

    colors = ["b", "r", "m", "w", "k", "g", "c", "y"] 
    to_use_colors = [] 
    information = [] 


    for index in xrange(0, len(Y)): 
     y = Y[index] 

     if index > len(colors): 
      to_use_colors.append(colors[0]) 
     else: 
      to_use_colors.append(colors[index]) 

     unique, counts = np.unique(y, return_counts=True) 
     unique_count = np.empty(shape=(unique.shape[0], 2), dtype=np.uint32) 

     for x in xrange(0, unique.shape[0]): 
      unique_count[x, 0] = unique[x] 
      unique_count[x, 1] = counts[x] 

     information.append(unique_count) 

    unique, counts = np.unique(Y[0], return_counts=True) 
    histrange = [np.min(unique), np.max(unique) + 1] 
    # the histogram of the data 
    n, bins, patches = plt.hist(Y, 1000, normed=False, alpha=0.75, range=histrange, label=labels) 


    #xticks_pos = [0.5 * patch.get_width() + patch.get_xy()[0] for patch in patches] 

    #plt.xticks(xticks_pos, unique) 

    plt.xlabel(xLabel) 
    plt.ylabel(yLabel) 
    plt.title(title) 
    plt.grid(True) 
    plt.legend() 

이 생산되어 3,124,928,582,316,

- 새로운 편집 :

def generate_histogram_from_array_of_labels(Y=[], labels=[], xLabel="Class/Label", yLabel="Count", title="Histogram of Trainset"): 
    plt.figure() 
    plt.clf() 

    information = [] 

    for index in xrange(0, len(Y)): 
     y = Y[index] 

     unique, counts = np.unique(y, return_counts=True) 
     unique_count = np.empty(shape=(unique.shape[0], 2), dtype=np.uint32) 

     for x in xrange(0, unique.shape[0]): 
      unique_count[x, 0] = unique[x] 
      unique_count[x, 1] = counts[x] 

     information.append(unique_count) 

    n, bins, patches = plt.hist(Y, normed=False, alpha=0.75, label=labels) 

    plt.xticks((0.25, 0.75), (0, 1)) 

    plt.xlabel(xLabel) 
    plt.ylabel(yLabel) 
    plt.title(title) 
    plt.grid(True) 
    plt.legend() 
지금 작동하고 있지만, 왼쪽에서 레이블 범위를 벗어 좀하고 난 것을 어떻게 할 수 ... 더 바의 중심을 원했다 ?

결과 : enter image description here

+0

'bins' 매개 변수를 제거했습니다. 기본적으로 10으로 설정되어 있습니다. 다음과 같이 빈 매개 변수를 추가하면됩니다. - n, bins, patches = plt.hist (Y, bins = 2, normed = False, alpha = 0.75, range = histrange, label = labels)' – hashcode55

+0

bin을 2로 설정해 보셨습니까? – hashcode55

+0

그리고 해당 레이블이 표시되지 않는 것에 대해서는 해당 컴퓨터의 특정 문제를 추측합니다. 당신은 subplot을 조정 해 볼 수 있습니다 ... 이것 좀 봐 http://matplotlib.org/examples/pylab_examples/subplots_adjust.html – hashcode55

답변

6

나는 노력이 함께했다. 코드에서 xticks 위치를 변경할 수 있습니다. 단순히 당신이해야 할 일은 plt.hist에 터플을 전달하는 것입니다. 더 간단하지 않을 수 있습니다.그래서 당신은 0과 1의 두 개의 목록이 있다고 가정 할 수 있습니다, 그래서 당신이 가야 할 것은 -

a = np.random.randint(2, size=1000) 
b = np.random.randint(2, size=1000) 
plt.hist((a, b), 2, label = ("data1", "data2")) 
plt.legend() 
plt.xticks((0.25, 0.75), (0, 1)) 

enter image description here

내가 (2 쓰레기통의 수를 변경 한 후) 실행하려고 정확한 코드 -

당신의 데이터 세트가 동일한 길이의 경우
a = np.random.randint(2, size=1000) 
b = np.random.randint(2, size=1000) 
y = [a, b] 
labels = ["data1", "data2"] 
generate_histogram_from_array_of_labels(Y = y, labels = labels) 

AAND 내가 같은 결과를 얻었다 ...

+0

그것은 지금 작동 한 것 같습니다! 그러나이 사소한 문제를 해결하도록 도와 줄 수 있습니까? 나는 xlabels에 막대를 더 잘 중심에두고 싶었다! 또한 왼쪽 레이블이 범위를 벗어났습니다! – KenobiShan

1

, 당신은 팬더와 함께 쉽게 할 수 있습니다.

automatic count graph with pandas

당신은 또한 import seaborn, 그것은 조금 더 좋은 보인다면 : 그래서 가정 당신은 당신은 단순히이 음모에 결과

import pandas 

df = pandas.DataFrame(list(zip(*Y)), columns=['Train', 'Validation', 'Test']) 
df.apply(pandas.value_counts).plot.bar() 

을 할 수

import numpy 

N = 1000 
train, validation, test = [numpy.random.randint(2, size=N) for _ in range(3)] 
Y = [train, validation, test] 

automatic count graph with seaborn

+0

이미지를 저장해야합니다. 제시 한 코드로 가능합니까? – KenobiShan

+0

@ScientistGirl 예, 평상시처럼 savefig를 사용하십시오. – chthonicdaemon