简体   繁体   English

matplotlib barh:如何在两组条之间制作视觉间隙?

[英]matplotlib barh: how to make a visual gap between two groups of bars?

I have some sorted data of which I only show the highest and lowest values in a figure.我有一些排序的数据,我只在图中显示最高和最低值。 This is a minimal version of what currently I have:这是我目前拥有的最小版本:

import matplotlib.pyplot as plt

# some dummy data (real data contains about 250 entries)
x_data = list(range(98, 72, -1))
labels = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
ranks = list(range(1, 27))

fig, ax = plt.subplots()

# plot 3 highest entries
bars_top = ax.barh(labels[:3], x_data[:3])
# plot 3 lowest entries
bars_bottom = ax.barh(labels[-3:], x_data[-3:])

ax.invert_yaxis()

# print values and ranks
for bar, value, rank in zip(bars_top + bars_bottom,
                            x_data[:3] + x_data[-3:],
                            ranks[:3] + ranks[-3:]):
    y_pos = bar.get_y() + 0.5
    ax.text(value - 4, y_pos, value, ha='right')
    ax.text(4, y_pos, f'$rank:\ {rank}$')

ax.set_title('Comparison of Top 3 and Bottom 3')
plt.show()

Result:结果:

在此处输入图像描述

I'd like to make an additional gap to this figure to make it more visually clear that the majority of data is in fact not displayed in this plot.我想在这个数字上做一个额外的差距,以便在视觉上更清楚地看到大部分数据实际上没有显示在这个 plot 中。 For example, something very simple like the following would be sufficient:例如,像下面这样非常简单的东西就足够了:

在此处输入图像描述

Is this possible in matplotlib?这在 matplotlib 中是否可行?

Here is a flexible approach that just plots a dummy bar in-between.这是一种灵活的方法,它只是在中间绘制一个虚拟条。 The yaxis-transform together with the dummy bar's position is used to plot 3 black dots. yaxis-transform 与 dummy bar 的 position 一起用于 plot 3 个黑点。

If multiple separations are needed, they all need a different dummy label, for example repeating the space character.如果需要多个分隔符,它们都需要不同的虚拟 label,例如重复空格字符。

import matplotlib.pyplot as plt
import numpy as np

# some dummy data (real data contains about 250 entries)
x_data = list(range(98, 72, -1))
labels = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
ranks = list(range(1, 27))

fig, ax = plt.subplots()

# plot 3 highest entries
bars_top = ax.barh(labels[:3], x_data[:3])
# dummy bar inbetween
dummy_bar = ax.barh(" ", 0, color='none')
# plot 3 lowest entries
bars_bottom = ax.barh(labels[-3:], x_data[-3:])

ax.invert_yaxis()

# print values and ranks
for bar, value, rank in zip(bars_top + bars_bottom,
                            x_data[:3] + x_data[-3:],
                            ranks[:3] + ranks[-3:]):
    y_pos = bar.get_y() + 0.5
    ax.text(value - 4, y_pos, value, ha='right')
    ax.text(4, y_pos, f'$rank:\ {rank}$')

# add three dots using the dummy bar's position
ax.scatter([0.05] * 3, dummy_bar[0].get_y() + np.linspace(0, dummy_bar[0].get_height(), 3),
           marker='o', s=5, color='black', transform=ax.get_yaxis_transform())

ax.set_title('Comparison of Top 3 and Bottom 3')
ax.tick_params(axis='y', length=0) # hide the tick marks
ax.margins(y=0.02) # less empty space at top and bottom
plt.show()

hbar 与条之间的分隔

The following function,以下function,

def top_bottom(x, l, n, ax=None, gap=1):
    from matplotlib.pyplot import gca

    if n <= 0 : raise ValueError('No. of top/bottom values must be positive') 
    if n > len(x) : raise ValueError('No. of top/bottom values should be not greater than data length')
    if n+n > len(x):
        print('Warning: no. of top/bottom values is larger than one'
              ' half of data length, OVERLAPPING')
    if gap < 0 : print('Warning: some bar will be overlapped')
        
    ax = ax if ax else gca()
    
    top_x = x[:+n]
    bot_x = x[-n:]
    top_y = list(range(n+n, n, -1))
    bot_y = list(range(n-gap, -gap, -1))
    top_l = l[:+n] # A B C
    bot_l = l[-n:] # X Y Z

    top_bars = ax.barh(top_y, top_x)
    bot_bars = ax.barh(bot_y, bot_x)

    ax.set_yticks(top_y+bot_y)
    ax.set_yticklabels(top_l+bot_l)

    return top_bars, bot_bars

when invoked with your data and n=4 , gap=4当使用您的数据和n=4调用时, gap=4

bars_top, bars_bottom = top_bottom(x_data, labels, 4, gap=4)

produces生产

在此处输入图像描述

Later, you'll be able to customize the appearance of the bars as you like using the Artists returned by the function.稍后,您将能够使用 function 返回的 Artists 自定义条形的外观。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM