Ash*_*ams 4 python label matplotlib bar-chart
到目前为止,这是我的基本代码:
我想放进Disease酒吧
import matplotlib
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
x = [u'Rimegepant',u'Rimegepant',u'Zavegepant',u'Zavegepant',u'Troriluzole',u'Troriluzole',u'Troriluzole',u'Verdiperstat',u'Verdiperstat']
y = [4,3,3,3,2,3,3,3,3]
Disease = ['Acute Treatment of Migraine','Preventive Treatment of Migraine','Acute and Preventive Migraine','Lung Inflammation COVID-19',"Alzheimer's Disease", "OCD", "Spinocerebellar Ataxia", "Multiple System Atrophy", "Amyotrophic Lateral Sclerosis"]
fig, ax = plt.subplots()
width = 0.75 # the width of the bars
ind = np.arange(len(y)) # the x locations for the groups
ax.barh(ind, y, width, color="green", align='edge')
ax.set_yticks(ind+width/2)
ax.set_yticklabels(x, minor=False)
plt.xticks(np.arange(5),('Pre-clinical','Phase I','Phase II','Phase III', 'Approved'))
plt.margins(0,0.05)
plt.title('BHVN')
plt.ylabel('Drug')
plt.show()
Run Code Online (Sandbox Code Playgroud)
您可以通过 matplotlib 将文本添加到 ax 中,如ax.text().
如果你添加
for bar, disease in zip(ax.patches, Disease[::-1]):
ax.text(0.1, bar.get_y()+bar.get_height()/2, disease, color = 'white', ha = 'left', va = 'center')
Run Code Online (Sandbox Code Playgroud)
plt.show()在您的代码之前,您将得到:
请注意,我必须颠倒您的Disease列表(使用 [::-1]),以便文本以您在图像中的方式显示,否则肌萎缩侧索硬化症位于顶部,偏头痛的急性治疗位于底部。
函数通用形式为plt.text(x, y, text),因此您会看到我将 x 偏移了 0.1,并从条形补丁中获取 y。
有关该函数的更多信息,您可以在此处查看matplotlib 文档