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

标签 python matplotlib

我有两个列表,一个是名称,另一个是值。我希望 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')  

感谢任何帮助!

最佳答案

ax.text 可用于将文本放置在给定的 x 和 y 位置。为了适合垂直条,文本应旋转 90 度。文本可以从顶部开始,也可以将 anchor 放在底部。对齐方式应分别为顶部或底部。可以选择适合图像的字体大小。文本颜色应该与条形颜色形成足够的对比。可以使用额外的空间来填充一些内容。

或者,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()

resulting plot

关于python - 将名称放在python条形图中的条形图中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60576298/

相关文章:

python - 部分 HTML 对 Scrapy 不可见

python - Matplotlib:将颜色条添加到不可映射的对象

python-2.7 - Matplotlib - 网格总是在 ax-h/v-lines 前面

python - matplotlib 的 pcolor 中的白线

python-3.x - matplotlib:用表情符号标签注释图

python - set_yticks 和 ylim 用于分类变量

python - 正则表达式 python - 查找子字符串

Python Imaging Library (PIL) 绘图--带渐变的圆角矩形

python - 在 Python 中创建 HDF5 数据集时如何处理可变大小的数组?

python - 这些networkx错误表示在 Pandas 数据帧上设置过滤器后得到什么?