2014-02-24 62 views
0

我有这个代码,生成这个图,但文字是如此非常关闭。我尝试了水平和垂直调整和旋转以使其可读性没有成功。matplotlib.pyplot覆盖在酒吧上的轴标签

是否有人可以告诉我如何重新定位文本并选择更好的字体/大小以使其可读?

任何关于更好的图表用于显示此数据的建议是非常受欢迎的。

enter image description here

import matplotlib.pyplot as plt 

N = 13 
ind = np.arange(N) 
width = 0.8 

good=[0, 1, 28, 144, 0, 41, 23, 5, 7, 2, 3, 9, 48] 
bad=[0, 1, 28, 144, 0, 41, 23, 5, 7, 2, 3, 9, 48] 
keys=[u'gaming', u'recreation', u'business', u'computer_internet', u'unknown', u'culture_politics', u'science_technology', u'law_crime', u'sports', u'religion', u'weather', u'health', u'arts_entertainment'] 
c2='r' 
c1='b' 
p1 = plt.bar(ind, good, width, color=c1) 
p2 = plt.bar(ind, bad, width, color=c2, bottom=good) 

plt.ylabel('Number of URLs scanned') 
plt.title('Category') 
plt.xticks(ind+width/2., keys, rotation='vertical') 
#plt.yticks(np.arange(0,81,10), rotation='vertical') 
plt.legend((p1[0], p2[0]), ('good', 'bad')) 

plt.show() 
+0

你能澄清你所说的“太惨了断”是什么意思?只是在保存这个数字时它会被截断? – mwaskom

+0

不,即使它出现在底部,它太长了,并使图形看起来不对。我也许不能,如果我们可以将标签垂直移动到酒吧旁边? – Kiarash

回答

1

你可以尝试一个水平的barplot。它通常对这种可视化效果更好。我也做了一些调整的类别进行排序,并使用更好的颜色:

import numpy 
import matplotlib.pyplot as plt 

good = np.array([0, 1, 28, 144, 0, 41, 23, 5, 7, 2, 3, 9, 48]) 
bad = np.array([0, 1, 28, 144, 0, 41, 23, 5, 7, 2, 3, 9, 48]) 
keys = np.array([u'gaming', u'recreation', u'business', u'computer_internet', 
       u'unknown', u'culture_politics', u'science_technology', 
       u'law_crime', u'sports', u'religion', u'weather', 
       u'health', u'arts_entertainment']) 
ind = np.arange(1, len(keys) + 1) 

order = np.argsort(good + bad) 
good, bad, keys = good[order], bad[order], keys[order] 

c2 = '#FF7777' 
c1 = '#7777FF' 
p1 = plt.barh(ind, good, color=c1, align="center", label="good") 
p2 = plt.barh(ind, bad, color=c2, left=good, align="center", label="bad") 

plt.xlabel('Number of URLs scanned') 
plt.yticks(ind, keys) 
plt.legend(loc="center right") 
plt.tight_layout() 

enter image description here

1

尝试以下一些调整底部边距:

plt.tight_layout()fig.savefig(bbox_inches='tight'),试图让matplotlib解决它自身。

您可以手动调整边距

#adjust these as needed 
plt.subplots_adjust(bottom=0.1, top=0.9, left=0.05, right=0.95) 

编辑:

如果你宁愿把标签上的情节旁边的酒吧,你可以这样做

N = 13 
width = 0.4 
ind = np.arange(N) + 0.5 #this puts the bars on the right of each "bin" 
p1 = plt.bar(ind, good, width, color=c1) 
p2 = plt.bar(ind, good, width, color=c2, bottom=good) 
for rect, key in zip(p1, keys): 
    x, y = rect.get_xy() 
    plt.text(x-width, y, text, va='bottom', ha='left', rotation=90) 

您可能需要在y坐标中添加一点缓冲区(如y+0.01或其他)。