如何给 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()输出
输入条形数:5

广告内容
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
JavaScript
PHP