如何在python的条形图中调整条形值的位置?

2024-04-26 01:36:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想移动条形图中的条形值,以便它们不会相互合并。我的代码如下。你知道吗

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

下面给出了该代码的结果。你知道吗

bar values are merged.

在我的图像中我想要的是下面给出的东西,在这里我可以以这样一种方式替换条值,即它们既不合并也不清晰可见。你知道吗

注意:应该注意的是,我希望我的图像宽度是相同的。你知道吗

my desired ouput


Tags: therectimportfigpltaxwidthnr
1条回答
网友
1楼 · 发布于 2024-04-26 01:36:51

既然你不想增加体形大小,这里有一个手动的廉价方法来获得你想要的。我只是粘贴修改过的代码。其余所有内容与代码保持一致。最后我还缩短了你的set_color部分。注:由于某些可视化/保存图形,条形图的宽度看起来不同。在我的屏幕上,它们看起来都一样宽。你知道吗

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

输出

enter image description here

相关问题 更多 >