如何使标签仅出现在特定条形上方

时间:2019-04-14 20:12:40

标签: python-3.x matplotlib label bar-chart

我想在此图表内的某些柱上方添加自定义标签。在此示例中,如何将标签仅添加到第4条和第8条:

import pandas as pd
import matplotlib.pyplot as plt

# Bring some raw data.
frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that, 
# so for consistency I create a series from the list.
freq_series = pd.Series.from_array(frequencies)

x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
            121740.0, 123980.0, 126220.0, 128460.0, 130700.0]

# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='bar')
ax.set_title('Amount Frequency')
ax.set_xlabel('Amount ($)')
ax.set_ylabel('Frequency')
ax.set_xticklabels(x_labels)

rects = ax.patches

# Make some labels.
labels = ["label%d" % i for i in xrange(len(rects))]

for rect, label in zip(rects, labels):
    height = rect.get_height()
    ax.text(rect.get_x() + rect.get_width() / 2, height + 5, label,
            ha='center', va='bottom')

使用此代码,我在每个小节上方都有一个标签。但是我只希望在第四和第八栏上方放置标签(例如,值分别为34和55)。

完成此任务的最佳方法是什么?

在这里找到以下示例:Adding value labels on a matplotlib bar chart

1 个答案:

答案 0 :(得分:3)

该代码是为Python 2和pandas的早期版本编写的;我对它进行了一些修改以使其适用于Python 3。

还有其他方法可以执行此操作,但是无需过多更改代码的结构,您可以做的是指定要绘制的条形标签的索引,如下所示which,然后对其进行绘制仅当它们对应时:

import pandas as pd
import matplotlib.pyplot as plt

# Bring some raw data.
frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that, 
# so for consistency I create a series from the list.
freq_series = pd.Series(frequencies)

x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
            121740.0, 123980.0, 126220.0, 128460.0, 130700.0]

# Plot the figure.
fig, ax = plt.subplots(figsize=(12, 8))
freq_series.plot(kind='bar', ax=ax)
ax.set_title('Amount Frequency')
ax.set_xlabel('Amount ($)')
ax.set_ylabel('Frequency')
ax.set_xticklabels(x_labels)

rects = ax.patches

# Make some labels.
labels = [f'label{i}' for i in range(len(rects))]

which = [3, 7]

for index, rect in enumerate(rects):
    if index in which:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width() / 2, height + 5, height,
                ha='center', va='bottom')

enter image description here