简体   繁体   English

不能给酒吧不同 colors

[英]Can't give bars different colors

My question is based on this answer: Adding value labels on a matplotlib bar chart我的问题是基于这个答案: 在 matplotlib bar chart 上添加值标签

In the answer by @oleson the bars are shown with different colors but when I run my code, I only see blue bars.在@oleson 的回答中,条形显示不同的 colors 但是当我运行我的代码时,我只看到蓝条。 Here is my code:这是我的代码:

import matplotlib.pyplot as plt
# Bring some raw data.
frequencies = [6, -16, 75, 160, 244, 260, 145, 73, 16, 4, 1]

freq_series = pd.Series(frequencies)

y_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='barh')
ax.set_title('Amount Frequency')
ax.set_xlabel('Frequency')
ax.set_ylabel('Amount ($)')
ax.set_yticklabels(y_labels)
ax.set_xlim(-40, 300) # expand xlim to make labels easier to read

rects = ax.patches

# For each bar: Place a label
for rect in rects:
    # Get X and Y placement of label from rect.
    x_value = rect.get_width()
    y_value = rect.get_y() + rect.get_height() / 2

    # Number of points between bar and label. Change to your liking.
    space = 5
    # Vertical alignment for positive values
    ha = 'left'

    # If value of bar is negative: Place label left of bar
    if x_value < 0:
        # Invert space to place label to the left
        space *= -1
        # Horizontally align label at right
        ha = 'right'

    # Use X value as label and format number with one decimal place
    label = "{:.1f}".format(x_value)

    # Create annotation
    plt.annotate(
        label,                      # Use `label` as label
        (x_value, y_value),         # Place label at end of the bar
        xytext=(space, 0),          # Horizontally shift label by `space`
        textcoords="offset points", # Interpret `xytext` as offset in points
        va='center',                # Vertically center label
        ha=ha)                      # Horizontally align label differently for
                                    # positive and negative values.

plt.savefig("image.png")

and here is what I get by running the exact same code:这是我通过运行完全相同的代码得到的结果: 在此处输入图像描述

I want it to look like this:我希望它看起来像这样: 在此处输入图像描述

Modify your code as per following instruction and you will get colored bar graph.按照以下说明修改您的代码,您将获得彩色条形图。

color = ['r','b','g','y','c']  #you can add custom colors

# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='barh',color=color)

Matplotlib is a pain to work with directly. Matplotlib直接使用起来很痛苦。 Try out Seaborn and you'll get nice plot out-of-the-box with just a few lines of code.试用Seaborn ,只需几行代码,您就会得到很好的开箱即用的 plot。

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

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