如何给 Pandas/Matplotlib 条形图自定义颜色?


要自定义颜色,我们可以创建一个十六进制字符串。从中,我们可以创建不同颜色表示形式的集合,并将其传递到 scatter 方法中以获取所需的输出。

使用 set_color 方法,我们可以设置条形的颜色。

步骤

  • 获取用户输入的条形数。

  • 使用 plt.bar() 方法添加条形。

  • 通过选择随机字符从十六进制字母中创建颜色。

  • 使用 set_color() 方法设置每个条形的颜色。

  • 要显示图形,我们可以使用 plt.show() 方法。

示例

from matplotlib import pyplot as plt
import random

bar_count = int(input("Enter number of bars: "))

bars = plt.bar([i for i in range(1, bar_count+1)], [i for i in range(1, bar_count+1)])

hexadecimal_alphabets = '0123456789ABCDEF'
colors = ["#" + ''.join([random.choice(hexadecimal_alphabets) for j in
range(6)]) for i in range(bar_count)]

for i in range(len(colors)):
   bars[i].set_color(colors[i])

plt.show()

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

输入条形数:5

更新时间: 2021 年 3 月 16 日

4 千+ 人浏览

开启您的职业生涯

通过完成课程获得认证

立即开始
广告内容