【问题标题】:How to write text inside the bar in a horizontal bar graph matplotlib?如何在水平条形图matplotlib中的条内写入文本?
【发布时间】:2021-06-24 11:19:17
【问题描述】:

到目前为止,我的代码给了我这样的东西:

如果可能的话,我想自己在酒吧里写下这样的东西:

到目前为止,这是我的基本代码:

我想把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()

【问题讨论】:

    标签: python matplotlib label bar-chart


    【解决方案1】:

    您可以通过 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') 
    

    就在您的代码中的plt.show() 之前,您将获得:

    注意,我必须颠倒您的 Disease 列表(使用 [::-1])才能使文本以您在图像中的方式出现,否则肌萎缩侧索硬化症排在首位,偏头痛的急性治疗排在首位底部。

    函数泛型形式来自plt.text(x, y, text),所以你看到我将 x 偏移 0.1 并从条形补丁中获取 y。

    有关该功能的更多信息,您可以查看matplotlib documentation here

    【讨论】:

      【解决方案2】:

      这样可以正常工作:

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

      【讨论】:

        【解决方案3】:
        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()
        

        您需要更改疾病列表的顺序才能正确显示

        【讨论】:

          猜你喜欢
          • 2021-07-31
          • 2017-07-25
          • 1970-01-01
          • 2016-07-14
          • 2013-05-15
          • 2012-03-26
          • 1970-01-01
          • 1970-01-01
          • 2017-11-21
          相关资源
          最近更新 更多