我有两个列表,其中一个是名称,另一个是值。我希望 y 轴为值,x 轴为名称。但是名称太长,无法放在轴上,这就是为什么我想将它们放入条形中,如图所示,但条形应该是垂直的。
在图片上,我的名单代表城市的名称。
我的输入是这样的:
mylist=[289.657,461.509,456.257]
nameslist=['Bacillus subtilis','Caenorhabditis elegans','Arabidopsis thaliana']
Run Code Online (Sandbox Code Playgroud)
我的代码:
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')
Run Code Online (Sandbox Code Playgroud)
任何帮助表示赞赏!
ax.text可用于将文本放置在给定的 x 和 y 位置。为了适合垂直条,文本应旋转 90 度。文本可以从顶部开始,也可以将其锚点放在底部。对齐方式应分别为顶部或底部。可以选择字体大小以适合图像。文本颜色应与条形颜色形成足够的对比。可以使用额外的空间来进行一些填充。
另外,还有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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1866 次 |
| 最近记录: |