我是matplotlib
的初学者,我正在尝试绘制两个条形图。对于第二张图,xlabels很好,但是对于第一张图,我得到了xlabels作为列表,它们也具有unicode字符串格式。这是我的代码:
def get_val_from_dict(objects, n):
x = []
y = []
for k,v in objects.items():
probalities = float(v)/n
cat = k
x.append(cat)
y.append(probalities)
return x,y
我的x
,y
列表的两个数据文件格式如下:
[u'fast_food', u'school', u'bar', u'beauty', u'hairdresser', u'park', u'hotel', u'kiosk', u'pub', u'nightclub', u'supermarket', u'restaurant', u'bakery', u'pharmacy', u'doctors', u'fitness_centre', u'cafe', u'bank', u'clothes']
[0.08, 0.03, 0.03, 0.01, 0.05, 0.03, 0.19, 0.12, 0.04, 0.01, 0.01, 0.25, 0.03, 0.01, 0.02, 0.02, 0.05, 0.01, 0.02]
[u'fast_food', u'school', u'bar', u'jewelry', u'beauty', u'hairdresser', u'shoes', u'park', u'museum', u'restaurant', u'kiosk', u'supermarket', u'pharmacy', u'bakery', u'greengrocer', u'cafe', u'bank', u'clothes']
[0.03, 0.03, 0.03, 0.03, 0.03, 0.15, 0.03, 0.09, 0.03, 0.21, 0.06, 0.03, 0.03, 0.06, 0.03, 0.06, 0.06, 0.03]
x_all = []
y_all = []
name_ = []
for arg in sys.argv[1:]:
reload(sys)
sys.setdefaultencoding('utf-8')
fp = open(arg)
contents = fp.read()
name = arg
n, data = subsamples(contents)
x, y = get_val_from_dict(data, n)
x_all.append(x)
y_all.append(y)
name_.append(name)
count=0
for i in range(len(x_all)):
count += 1
f, axarr = plt.subplots(count, sharex='col', sharey='row')
for i in range(len(x_all)):
axarr[i].set_title(label ="%s" %(name_[i]))
axarr[i].bar(x_all[i], y_all[i])
axarr[i].tick_params(axis='both', which='both')
axarr[i].set_xlabel(x)
axarr[i].set_xticklabels(x_all[i], rotation=90)
plt.show()
如何将第一个子图绘制为下面的图?
答案 0 :(得分:0)
通常,因为使用sharex
,所以在第一个条形图下方不会出现任何标签。因此,您看到的是axarr[i].set_xlabel(x)
设置的列表。现在x
并没有真正在代码中的这个位置使用;这是您通过x, y = get_val_from_dict(data, n)
获得的列表。我想您只是想从代码中删除行axarr[i].set_xlabel(x)
,或将其替换为更有用的内容
axarr[i].set_xlabel("My cool categories")
但是请注意,两个图的类别数量是不同的,因此在第一个图中您有一个未标记的条。所以我不想在这里分享轴。
import matplotlib.pyplot as plt
x1 = [u'fast_food', u'school', u'bar', u'beauty', u'hairdresser', u'park', u'hotel', u'kiosk', u'pub', u'nightclub', u'supermarket', u'restaurant', u'bakery', u'pharmacy', u'doctors', u'fitness_centre', u'cafe', u'bank', u'clothes']
y1 = [0.08, 0.03, 0.03, 0.01, 0.05, 0.03, 0.19, 0.12, 0.04, 0.01, 0.01, 0.25, 0.03, 0.01, 0.02, 0.02, 0.05, 0.01, 0.02]
x2 = [u'fast_food', u'school', u'bar', u'jewelry', u'beauty', u'hairdresser', u'shoes', u'park', u'museum', u'restaurant', u'kiosk', u'supermarket', u'pharmacy', u'bakery', u'greengrocer', u'cafe', u'bank', u'clothes']
y2 = [0.03, 0.03, 0.03, 0.03, 0.03, 0.15, 0.03, 0.09, 0.03, 0.21, 0.06, 0.03, 0.03, 0.06, 0.03, 0.06, 0.06, 0.03]
x_all = [x1,x2]
y_all = [y1,y2]
name_ = ["A", "B"]
fig, axarr = plt.subplots(len(x_all), sharey='row')
for i in range(len(x_all)):
axarr[i].set_title(label ="%s" %(name_[i]))
axarr[i].bar(x_all[i], y_all[i])
axarr[i].tick_params(axis='both', which='both')
axarr[i].set_xlabel("My cool categories")
axarr[i].set_xticklabels(x_all[i], rotation=90)
fig.tight_layout()
plt.show()