2017-12-29 4 views
0

간단한 질문이 있다고 생각하지만 제 생각에는 이것을 달성하는 데 도움이되는 블로그를 볼 수 없습니다. 나는 "시리즈"라고 불리는 파이썬 팬더 시리즈를 가지고 있으며, 히스토그램을 시각화하기 위해 series.hist()를 사용한다. 그래프에 직접 각 bin에 대한 발생 횟수를 시각화해야하지만이 문제에 대한 해결책을 찾을 수는 없습니다.그래프에서 matplotlib 히스토그램 빈 수를 직접 시각화하십시오

각 bin의 상단에 각 bin의 발생 횟수를 보여주는 레이블을 어떻게 표시합니까?

정확히 말하면,이 내 코드입니다 :

import matplotlib.pyplot as plt 
your_bins=10 
data = [df_5m_9_4pm.loc['2017-6']['sum_daily_cum_ret'].values] 
plt.hist(data, binds = your_bins) 
arr = plt.hist(data,bins = your_bins) 
for i in range(your_bins): 
    plt.text(arr[1][i],arr[0][i],str(arr[0][i])) 

나는 단순히 "데이터"변수를 인쇄하면이처럼 보이는 방법이다 : 나는 위의 코드를 실행하면

[array([ 0.  , 0.03099187, -0.00417244, ..., -0.00459067, 
     0.0529476 , -0.0076605 ])] 

--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 
<ipython-input-97-917078981b1d> in <module>() 
     2 your_bins=10 
     3 data = [df_5m_9_4pm.loc['2017-6']['sum_daily_cum_ret'].values] 
----> 4 plt.hist(data, binds = your_bins) 
     5 arr = plt.hist(data,bins = your_bins) 
     6 for i in range(your_bins): 

~/anaconda3/lib/python3.6/site-packages/matplotlib/pyplot.py in hist(x, bins, range, density, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, normed, hold, data, **kwargs) 
    3002      histtype=histtype, align=align, orientation=orientation, 
    3003      rwidth=rwidth, log=log, color=color, label=label, 
-> 3004      stacked=stacked, normed=normed, data=data, **kwargs) 
    3005  finally: 
    3006   ax._hold = washold 

~/anaconda3/lib/python3.6/site-packages/matplotlib/__init__.py in inner(ax, *args, **kwargs) 
    1708      warnings.warn(msg % (label_namer, func.__name__), 
    1709         RuntimeWarning, stacklevel=2) 
-> 1710    return func(ax, *args, **kwargs) 
    1711   pre_doc = inner.__doc__ 
    1712   if pre_doc is None: 

~/anaconda3/lib/python3.6/site-packages/matplotlib/axes/_axes.py in hist(***failed resolving arguments***) 
    6205    # this will automatically overwrite bins, 
    6206    # so that each histogram uses the same bins 
-> 6207    m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs) 
    6208    m = m.astype(float) # causes problems later if it's an int 
    6209    if mlast is None: 

~/anaconda3/lib/python3.6/site-packages/numpy/lib/function_base.py in histogram(a, bins, range, normed, weights, density) 
    665  if mn > mx: 
    666   raise ValueError(
--> 667    'max must be larger than min in range parameter.') 
    668  if not np.all(np.isfinite([mn, mx])): 
    669   raise ValueError(

ValueError: max must be larger than min in range parameter. 
+0

@coldspeed - 해당 링크의 솔루션이 제 끝에서 작동하지 않습니다. 오류 메시지가 나타납니다. – Andrea

+0

해당 코드를 사용하여 얻는 오류 메시지는 다음과 같습니다. "ValueError : max는 range 매개 변수에서 min보다 커야합니다." – Andrea

+0

질문을 다시 열었습니다. –

답변

1

이 시도 :

를, 나는 오류 메시지가 Labeled bins

대신 주파수의 원시 발생을 원하는 경우에

import matplotlib.pyplot as plt    
import numpy as np          


x = np.random.normal(size = 1000)           
counts, bins, patches = plt.hist(x, normed=True) 
plt.ylabel('Probability') 

# Label the raw counts and the percentages below the x-axis... 
bin_centers = 0.5 * np.diff(bins) + bins[:-1] 
for count, x in zip(counts, bin_centers): 
    # Label the raw counts 
    plt.annotate('{:.2f}'.format(count), xy=(x, 0), xycoords=('data', 'axes fraction'), 
     xytext=(0, 18), textcoords='offset points', va='top', ha='center') 

plt.show() 

, 단지 normed=True을 제거하고 어쩌면 형식 문자열을 변경합니다.

the question linked in the sidebar에 코드를 복사하고 (0, -18)(0, 18)으로 변경하여이 문제를 해결할 수 있다고 덧붙였습니다.

관련 문제