水平条形图:调整y轴标签大小

3 投票
1 回答
1683 浏览
提问于 2025-04-18 16:02

我在使用pandas的时候,想做一个横向条形图,但发现y轴的标签被截断了。

我用的数据是……

Term                                                           value
GO:0043232~intracellular non-membrane-bounded organelle    69.40887024
GO:0043228~non-membrane-bounded organelle                  68.41919153
GO:0051384~response to glucocorticoid stimulus              58.50901338
hsa04310:Wnt signaling pathway                             24.56895837
GO:0016055~Wnt receptor signaling pathway                   18.00929324
GO:0042127~regulation of cell proliferation             5.215295969

y轴的标签我用了“Term”这一列。

我的代码是……

    a=list(final_table['value'])
    b=list(final_table['Term'])
    data=pd.DataFrame(a,index=b,columns=['value'])
    data[:31].plot(kind='barh',color='k',alpha=0.7)
    matplotlib.pyplot.savefig('test.png')

横向条形图的例子看起来是这样的:

我该怎么解决这个问题呢?除了保存图片,我还尝试用pandas和XlsxWriter把图写到Excel文件里(pandas和XlsxWriter),但好像XlsxWriter没有绘制横向条形图的功能。

1 个回答

3

你可以这样做:

In [1]: data
Out[1]: 
                                                             value
Term                                                              
GO:0043232~intracellular non-membrane-bounded organelle  69.408870
GO:0043228~non-membrane-bounded organelle                68.419192
GO:0051384~response to glucocorticoid stimulus           58.509013
hsa04310:Wnt signaling pathway                           24.568958
GO:0016055~Wnt receptor signaling pathway                18.009293
GO:0042127~regulation of cell proliferation               5.215296


In [2]: data.plot(kind="barh", fontsize=9, figsize=(15,8)) 
In [3]: plt.yticks(range(6), 
                   ["\n".join(
                              [" ".join(i.split("~")[:-1]),
                              "\n".join(i.split("~")[-1].split(" "))])
                   for i in a.index])

barh

这里你可以通过以下方式来腾出空间:

  • 减小字体大小
  • 增大图形尺寸
  • 把你的文本分成不同的行:

.

"\n".join([

" ".join(i.split("~")[:-1]), # everything before the "~" () actually [0] but since the 4th line has no "~", I put all but last to avoid redundancy.

"\n".join(i.split("~")[-1].split(" ")) # here line break every word.

])

希望这能帮到你,如果你有问题,随时问我。

撰写回答