简体   繁体   English

如何在水平条形图 matplotlib 的条内写入文本?

[英]How to write text inside the bar in a horizontal bar graph matplotlib?

My code so far gives me something that looks like this:到目前为止,我的代码给了我一些看起来像这样的东西: 在此处输入图像描述

I am wanting to write in the bars themselves if possible to get something like this:如果可能的话,我想自己在酒吧里写下这样的东西: 在此处输入图像描述

Here's my base code so far:到目前为止,这是我的基本代码:

I'd like to put Disease into the bar我想把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()

You can add text to the ax via matplotlib as ax.text() .您可以通过 matplotlib 将文本添加到ax.text()中。

If you add如果你添加

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

just before plt.show() in your code, you'll get:就在代码中的plt.show()之前,您将获得:

在此处输入图像描述

Note, I had to reverse your Disease list (using [::-1]) for text to appear the way you have in your image, otherwise Amyotrophic Lateral Sclerosis is on top, and Acute Treatment of Migraine on the bottom.请注意,我必须颠倒您的Disease列表(使用 [::-1])以使文本以您在图像中的方式显示,否则肌萎缩侧索硬化症在顶部,偏头痛的急性治疗在底部。

Function generic form comes in plt.text(x, y, text) , so you see I offset x by 0.1 and get y from the bar patch. Function 通用形式来自plt.text(x, y, text) ,所以你看到我将 x 偏移 0.1 并从条形补丁中获取 y。

For extra information on the function, you can check out matplotlib documentation here有关 function 的更多信息,您可以在此处查看 matplotlib 文档

This will work fine:这将正常工作:

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"]
Disease.reverse()
fig, ax = plt.subplots()
width = 0.75 # the width of the bars
ind = np.arange(len(y))  # the x locations for the groups
bar_plot = 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'))

def autolabel(bar_plot):
    for idx,rect in enumerate(bar_plot):
        ax.text(0.25, idx+.25, Disease[idx], color = 'white')
autolabel(bar_plot)

plt.margins(0,0.05)
plt.title('BHVN')
plt.ylabel('Drug')

plt.show()
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

# I changed this line
p1 = ax.barh(ind,y, width, color="green", align='edge')
ax.set_yticks(ind+width/2)
ax.set_yticklabels(x, minor=False)

# I added this line
ax.bar_label(p1, Disease, label_type='center')
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()

You need to change the order of the disease list so it can show correctly您需要更改疾病列表的顺序才能正确显示

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

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