2010-08-12 45 views
5

任何人都知道是否有可能在matplotlib中包裝xtick標籤?現在我已經得到了下面的代碼(種凌亂 - 它被黑客攻擊了一會兒):是否有可能在python中包裝matplotlib中的xticks文本?

def plotResults(request, question_id): 
responses = ResponseOption.objects.filter(question__id=question_id).order_by('order').annotate(response_num=Count('response')) 

counts = [] 
labels = [] 

for response in responses: 
    counts.append(response.response_num) 
    labels.append(smart_truncate('$'+response.text+'$')) 

N = len(labels) 
labels = tuple(labels) 
counts = tuple(counts) 
ind = na.array(range(N))+0.5 
width = .35 
fig = Figure(facecolor='white',edgecolor='white') 
ax = fig.add_subplot(1,1,1) 


rects1 = ax.bar(ind, counts,linewidth=0) 

ax.set_ylabel('$Count$') 

ax.set_title('$Response Historgram$') 
ax.set_xticks(ind+width) 
ax.set_xticklabels(labels) 

print mpl.matplotlib_fname() 

canvas = FigureCanvas(fig) 
response = HttpResponse(content_type='image/png') 

canvas.print_png(response) 

return response 

生成此情節:

alt text

正如你所看到的xticks被粘結。關於如何包裝它們的任何想法,或者使它們可讀的瓶頸?再次感謝!

PS:這是一個Django項目的一部分。我將該情節作爲png圖片返回 - 通常在各種視圖中通過img標記調用它們。

+1

'rotation ='vertical'' could be the answer:http://stackoverflow.com/questions/1221108/barchart-with-vertical-labels-in-python-matplotlib – unutbu 2010-08-12 02:40:35

+1

@〜unutbu:''rotation' can be任何角度,請參閱:http://matplotlib.sourceforge.net/api/axes_api.html#matplotlib.axes.Axes.set_xlabel – Amro 2010-08-12 02:44:17

+0

@Amro,謝謝。 'xticks(rotation = 45)'看起來可能更好...... – unutbu 2010-08-12 02:48:33

回答

9

也許嘗試:

ax.set_xticklabels(labels, rotation=45) 

感謝AMRO爲指出rotation can be any degree

+1

或在一個調用中:'ax.set_xticklabels(labels,rotation = 45)':http://matplotlib.sourceforge.net/api/axes_api.html#matplotlib .axes.Axes.set_xticklabels – Amro 2010-08-12 02:54:02

+0

@Amro,再次感謝。如果您想發佈答案,我很樂意刪除我的。 – unutbu 2010-08-12 02:58:55

+0

那是好的,我想這是你的想法:) – Amro 2010-08-12 03:00:02

0

如果你想手動包裝標籤,你可以在標籤名稱中插入一個'\ n',這會在你有'\ n'的地方將標籤分成兩行。你可以看到這個here的例子。

現在似乎也有一個autowrap function,似乎很好地做的伎倆。這個例子使用plt.text,但它也是一個可以用plt.xticks指定的屬性。 (即wrap=True)我發現這種混亂的標籤對齊,所以我需要調整水平和垂直對齊。

相關問題