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

2024-10-02 18:16:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个列表,一个是名称,另一个是值。我希望y轴是值,x轴是名称。但是名字太长了,不能放在轴上,这就是为什么我想把它们放在横条上,就像图片上一样,但横条应该是垂直的enter image description here

在这张照片上,我的名单代表了城市的名字

我的意见如下:

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

我的代码:

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')  

感谢您的帮助


Tags: 名称列表fig图片ax名字widthlength
1条回答
网友
1楼 · 发布于 2024-10-02 18:16:00

^{}可用于将文本放置在给定的x和y位置。要适合垂直条,文本应旋转90度。文本可以从顶部开始,也可以在底部有其定位点。对齐方式应分别为顶部或底部。可以选择字体大小,使其与图像非常匹配。文本颜色应与条形图的颜色形成充分对比。可以使用额外的空间来进行填充

或者,还有^{}有更多的定位和装饰选项

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()

resulting plot

相关问题 更多 >