【问题标题】:How can I adjust the bar values placement in bar chart in python?如何在 python 的条形图中调整条形值的位置?
【发布时间】:2018-08-24 18:42:17
【问题描述】:

我想移动条形图中的条形值,以免它们相互合并。我的代码如下。

from __future__ import division
import matplotlib.pyplot as plt
import numpy as np

x = [0,1,2,3,4,5,6,7,8,9,10,11,12]
freq = [0.93, 0.87,0.86,0.87,0.93,0.84,0.74,0.79,0.78,0.95,0.88,0.8, 0.71]

width = 0.1 # width of the bars
xticklabels = ['NR-AHR','NR-AR','NR-AR-LBD','NR-Aromatase','NR-ER','NR-ER-LBD','NR-PPARG','SR-ARE','SR-HSE','SR-MMP','SR-P53','SR-ATAD5','AM']
fig, ax = plt.subplots()
rects1 = ax.bar(x, freq, width, color='b')
#xlabels=['X1', 'X2', 'X3', 'X4', 'X5', 'X6', 'X7', 'X8', 'X9', 'X10', 'X11', 'X12', 'X13']
ax.set_ylim(0.6,1)
ax.set_ylabel('auc-roc', fontsize=13)
#xlabels, rotation=45, rotation_mode="anchor"
ax.set_xticks(np.add(x,(width/2.2))) # set the position of the x ticks
ax.set_xticklabels(xticklabels,rotation = 75, ha="right")
#ax.set_xticklabels(xlabels, rotation=45)
def autolabel(rects):
    # attach some text labels
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/1., 1*height,
                '%.2f' %(height),
                ha='center', va='bottom')

autolabel(rects1)


rects1[0].set_color('r')
rects1[1].set_color('r')
rects1[2].set_color('r')
rects1[3].set_color('r')
rects1[4].set_color('r')
rects1[5].set_color('r')
rects1[6].set_color('r')
rects1[7].set_color('g')
rects1[8].set_color('g')
rects1[9].set_color('g')
rects1[10].set_color('g')
rects1[11].set_color('g')
rects1[12].set_color('b')
#fig = matplotlib.pyplot.gcf()
fig.set_size_inches(3.31, 3.5)
plt.savefig('Figure1.pdf', bbox_inches='tight')
plt.show() 

这段代码的结果如下。

我想要的图像如下所示,我可以在其中置换条形值,使其既不合并也不清晰可见。

注意:需要注意的是,我希望我的图像宽度相同。

【问题讨论】:

  • 增加图形大小?
  • 没有。这是最重要的约束。
  • 嗯,好的。您能否将其包含在问题中,因为它是一个重要部分?
  • 是的,我已经用注释编辑了我的问题。

标签: python matplotlib bar-chart


【解决方案1】:

由于您不想增加图形大小,这里有一个手动便宜的黑客来获得您想要的东西。我只是粘贴修改后的代码。休息一切都与您的代码相同。我还在最后缩短了你的set_color 部分。 P.S:由于一些可视化/保存图形,条形的宽度看起来不同。在我的屏幕上,它们看起来都一样宽。

def autolabel(rects):
    for i, rect in enumerate(rects):
        height = rect.get_height()
        if i == 2 or i ==7:
            ax.text(rect.get_x() + rect.get_width()/1., 1.07*height,
                '%.2f' %(height), ha='center', va='bottom')
            ax.vlines(rect.get_x() + rect.get_width()/3., 1.005*height, 1.07*height, lw=1, color='gray')
        else:    
            ax.text(rect.get_x() + rect.get_width()/1., 1.01*height,
                '%.2f' %(height), ha='center', va='bottom')

autolabel(rects1)

c = 7*['r'] + 5*['g'] + ['b'] 
for i, r in enumerate(rects1):
    r.set_color(c[i])

输出

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    • 2012-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多