简体   繁体   English

在python中的条形图中将名称放在条形图中

[英]Putting names inside bars in a bar plot in python

I have two lists, one of them is names, the other one is values.我有两个列表,其中一个是名称,另一个是值。 I want y axis to be values, x axis to be names.我希望 y 轴是值,x 轴是名称。 But names are too long to be put on axis, that's why I want to put them into bars, like on the picture, but bars should be vertical.但是名称太长而无法放在轴上,这就是为什么我想将它们放入条形中,就像图片一样,但条形应该是垂直的。 在此处输入图片说明

On the picture, my namelist represent names of cities.在图片上,我的名单代表城市名称。

My input is as such:我的输入是这样的:

mylist=[289.657,461.509,456.257]
nameslist=['Bacillus subtilis','Caenorhabditis elegans','Arabidopsis thaliana']

my code:我的代码:

fig = plt.figure()
width = 0.35
ax = fig.add_axes([1,1,1,1])
ax.bar(nameslist,mylist,width)
ax.set_ylabel('Average protein length')
ax.set_xlabel('Names')
ax.set_title('Average protein length by bacteria')  

Any help appreciated!任何帮助表示赞赏!

ax.text can be used to place text at a given x and y position. ax.text可用于在给定的 x 和 y 位置放置文本。 To fit into a vertical bar, the text should be rotated 90 degrees.为了适合垂直条,文本应旋转 90 度。 The text could either start at the top, or have its anchor point at the bottom.文本可以从顶部开始,也可以在底部有其锚点。 The alignment should be respectively top or bottom.对齐方式应分别为顶部或底部。 A fontsize can be chosen to fit well to the image.可以选择字体大小以适合图像。 The text color should be sufficiently contrasting to the color of the bars.文本颜色应与条形颜色形成鲜明对比。 An additional space can be used to have some padding.可以使用额外的空间来填充一些填充。

Alternatively, there is ax.annotate with more options for positioning and decorating.或者,有ax.annotate有更多的定位和装饰选项。

from matplotlib import pyplot as plt
import numpy as np

mylist = [289.657, 461.509, 456.257]
nameslist = ['Bacillus subtilis', 'Caenorhabditis elegans', 'Arabidopsis thaliana']

fig, ax = plt.subplots()
width = 0.35
ax.bar(nameslist, mylist, width, color='darkorchid')
for i, (name, height) in enumerate(zip(nameslist, mylist)):
    ax.text(i, height, ' ' + name, color='seashell',
            ha='center', va='top', rotation=-90, fontsize=18)
ax.set_ylabel('Average protein length')
ax.set_title('Average protein length by bacteria')
ax.set_xticks([]) # remove the xticks, as the labels are now inside the bars

plt.show()

结果图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM