多条形图y轴上的matplotlib中断

2024-09-30 14:25:09 发布

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

我试图在y轴上为下面的图创建一个断点。我尝试过使用brokenaxis方法(但我最终无法在我的栏上有标题,而且东西看起来不太好)和文档here,但我似乎无法让它工作。我要么最终创建了两个具有我想要的精确绘图但没有数据的图形,另一个图形与之前完全相同。有人能帮我吗?谢谢

from matplotlib import pyplot as plt
import numpy as np
from brokenaxes import brokenaxes

system_x = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
x_indexes = np.arange(len(system_x))

width = 0.2

fig, (ax) = plt.subplots()

cof_1 = [15, 0.0798, 0.0696, 0.0540, 0.0616, 0.0601, 0.0590]
cof_2 = [0.3856, 0.1428, 0.1803, 0.1694, 0.1172, 0.1913, 0.1474]
cof_3 = [1, 1, 2, 3, 1, 2, 2]
cof_4 = [0.0874, 0.0846, 0.0730, 0.1114, 0.0541, 0.0823, 0.0803]

r0 = ax.bar(x_indexes - 1.5*width, cof_1, label='1', color='crimson', width=width)
r1 = ax.bar(x_indexes - 0.5*width, cof_2, label='2', color='slategrey', width=width)
r2 = ax.bar(x_indexes + 0.5*width, cof_3,
            label='3', color='yellowgreen', width=width)
r3 = ax.bar(x_indexes + 1.5*width, cof_4, label='3', color='orange', width=width)


def autolabel(rects):

    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),
                    textcoords="offset points",
                    ha='center', va='bottom', rotation='vertical',
                    fontweight='bold')


autolabel(r0)
autolabel(r1)
autolabel(r2)
autolabel(r3)

plt.xticks(ticks=x_indexes, labels=system_x)

plt.xlabel('Test')
plt.ylabel('Test1')
plt.title('Mean Test')
axes = plt.gca()
axes.set_ylim([0, 10])

leg = plt.legend()

leg_lines = leg.get_lines()
leg_texts = leg.get_texts()

plt.setp(leg_lines, linewidth=4)

plt.grid(False)

plt.tight_layout()

plt.show()

Tags: rectimportgetbarpltaxwidthsystem
1条回答
网友
1楼 · 发布于 2024-09-30 14:25:09

既然您的数据具有不同的比例,为什么不在y上使用日志比例:

# modify auto label function
def autolabel(rects, vals):

    for rect,val in zip(rects,vals):
        height = rect.get_height()
        ax.annotate('{}'.format(val),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),
                    textcoords="offset points",
                    ha='center', va='bottom', rotation='vertical',
                    fontweight='bold')


autolabel(r0,cof_1)
autolabel(r1,cof_2)
autolabel(r2,cof_3)
autolabel(r3,cof_4)

# other codes
# ...

plt.xlabel('Test')
plt.ylabel('Test1')
plt.title('Mean Test')
plt.yscale('log')

# other codes
# ...

输出:

enter image description here

也可以考虑绘制水平条。

相关问题 更多 >