2014-05-08 7 views
3

내 논문의 그래프를 만들기 위해 matplotlib을 사용하고 있습니다. 이 같은matplotlib barplot의 마지막 막대가 반으로 채워짐

import numpy as np 
import numpy as np 
import matplotlib as mpl 
mpl.use('pgf') 

fig_width_pt = 390 # Get this from LaTeX using \showthe\columnwidth 
inches_per_pt = 1.0/72.27    # Convert pt to inch 
golden_mean = (np.sqrt(5)-1.0)/2.0   # Aesthetic ratio 
fig_width = fig_width_pt*inches_per_pt # width in inches 
fig_height = fig_width*golden_mean  # height in inches 
fig_size = [fig_width,fig_height] 

pgf_with_latex = {      # setup matplotlib to use latex for output 
    "pgf.texsystem": "pdflatex",  # change this if using xetex or lautex 
    "text.usetex": True,    # use LaTeX to write all text 
    "font.family": "serif", 
    "font.serif": [],     # blank entries should cause plots to inherit fonts from the document 
    "font.sans-serif": [], 
    "font.monospace": [], 
    "axes.labelsize": 10,    # LaTeX default is 10pt font. 
    "text.fontsize": 10, 
    "legend.fontsize": 8,    # Make the legend/label fonts a little smaller 
    "xtick.labelsize": 8, 
    "ytick.labelsize": 8, 
    "figure.figsize": fig_size, 
    'axes.linewidth': .5, 
    'lines.linewidth': .5, 
    'patch.linewidth': .5, 
    "pgf.preamble": [ 
     r"\usepackage[utf8x]{inputenc}", # use utf8 fonts becasue your computer can handle it :) 
     ] 
    } 
mpl.rcParams.update(pgf_with_latex) 

import matplotlib.mlab as mlab 
import matplotlib.pyplot as plt 
import colorsys 

def savefig(filename): 
    plt.savefig('{}.pgf'.format(filename)) 
    plt.savefig('{}.pdf'.format(filename)) 

# setup 
title = 'Clustering after salting out' 
ylabel = '% of total colloids' 
xlabel = 'Cluster size' 
xticklabels = ('1','2','3','4','5','6','7','5+') 
legend = ['10min', '20min','30min'] 

# read data from files 
# skipped this part for legibility 

# calculations with data, skipped for legibility 

# plot it in a bar plot 
N = len(ys[0]) 

ind = np.arange(0, N+1, 1.2) # the x locations for the groups 
width = 0.35  # the width of the bars 

# generate colours 
hsv_colours = [(x*1.0/N, 0.8, 0.8) for x in range(N)] 
rgb_colours = map(lambda x: colorsys.hsv_to_rgb(*x), hsv_colours) 

fig, ax = plt.subplots() 
rects = [ax.bar([x+i*width for x in ind], y, width, color=rgb_colours[i], yerr=errors_percentage[i]) for i,y in enumerate(ys)] 

# add some info 
ax.set_ylabel(ylabel) 
ax.set_xlabel(xlabel) 
ax.set_title(title) 
ax.set_xticks(ind+width) 
ax.set_xticklabels(xticklabels) 
ax.axis([0,7,0,60]) 
ax.legend(rects, legend) 

savefig('tpm_cluster_statistics') 

출력 생산 외모 : 당신이 볼 수 있듯이 Result of python code

, 막대 그래프의 마지막 줄이 완전히 작성되지 나는 다음과 같은 코드를 사용하고 있습니다. 작동 시키려면 다른 설정이 필요합니까? 목표는 LaTex 문서에 포함 할 PGF 파일을 만드는 것입니다. PDF 파일은 미리보기 용입니다. 부분적으로 채워진 막대는 모두 PDF와 PGF 파일에 있습니다. 도움을 주시면 대단히 감사하겠습니다!

편집 : 응답에서 가 tcaswell하기 :이 컴퓨터에 시도 할 수 있습니다 최소한의 작업 예입니다 minimal working example

그러나 때

import numpy as np 
import numpy as np 
import matplotlib as mpl 
mpl.use('pgf') 

pgf_with_latex = {      # setup matplotlib to use latex for output 
    "pgf.texsystem": "pdflatex",  # change this if using xetex or lautex 
    "text.usetex": True,    # use LaTeX to write all text 
    } 
mpl.rcParams.update(pgf_with_latex) 

import matplotlib.mlab as mlab 
import matplotlib.pyplot as plt 
import colorsys 

def savefig(filename): 
    plt.savefig('{}.pgf'.format(filename)) 
    plt.savefig('{}.pdf'.format(filename)) 

# setup 
title = 'Title' 
ylabel = 'x' 
xlabel = 'y' 
xticklabels = ('1','2','3','4','5','6','7','8') 
legend = ['1', '2','3'] 

#data 
ys = [[51.63593099345628, 28.911362284354553, 12.135633551457465, 4.521118381915526, 1.189767995240928, 0.7138607971445567, 0.41641879833432477, 0.4759071980963712], [46.66359871145882, 21.445006902899216, 14.496088357109988, 7.363092498849516, 4.1417395306028535, 3.313391624482283, 0.0, 2.577082374597331], [52.642595499738356, 22.39665096807954, 12.087912087912088, 7.744636316064887, 2.3547880690737837, 1.5698587127158554, 0.3663003663003663, 0.837257980115123]] 

# plot it in a bar plot 
N = len(ys[0]) 

ind = np.arange(0, N+1, 1.2) # the x locations for the groups 
width = 0.35  # the width of the bars 

fig, ax = plt.subplots() 
rects = [ax.bar([x+i*width for x in ind], y, width) for i,y in enumerate(ys)] 

# add some info 
ax.set_ylabel(ylabel) 
ax.set_xlabel(xlabel) 
ax.set_title(title) 
ax.set_xticks(ind+width) 
ax.set_xticklabels(xticklabels) 
ax.axis([0,7,0,60]) 
ax.legend(rects, legend) 

savefig('tpm_cluster_statistics') 

는 결과는 다음과 같습니다

다음 줄을 삭제합니다.

mpl.use('pgf') 

pgf_with_latex = {      # setup matplotlib to use latex for output 
    "pgf.texsystem": "pdflatex",  # change this if using xetex or lautex 
    "text.usetex": True,    # use LaTeX to write all text 
    } 
mpl.rcParams.update(pgf_with_latex) 

결과는 plt.show()을 사용하여 결과가 올바르게 표시됩니다.

+0

높이 값이 0이고 오류 막대가 아니라는 점을 제외하고 더미 데이터를 하나 더 추가하여 플롯 한 개를 추가하면 어떻게되는지보십시오. 클러스터 크기 6 30 분 막대가 채워지나요? – MattDMo

+0

답변 해 주셔서 감사합니다. 나는이 데이터를 사용했다 :'data = [[old_data0, 0.], [old_data1, 0.], [old_data2, 0.]] 그리고 errors = [[old_errors0, 0.], [old_errors1, 0.], [old_errors2 , 0.]]',하지만 차이점은 보이지 않습니다 ... – rbnvrw

+0

mpl의 버전은 무엇입니까? 이 코드를 재현하는데 필요한 최소한의 코드 (합성 데이터, 레이블 + 멋진 포맷)를 줄일 수 있습니까? – tacaswell

답변

0

정말 어떤 원인인지 모르지만 mpl.use('pgf')없이 PDF 출력으로 전환하면 문제가 해결됩니다. 지금은 PDF 만 사용 하겠지만 괜찮습니다. 모든 도움에 감사드립니다!