面试题答案
一键面试Matplotlib
Matplotlib设置柱状图柱子颜色可通过bar
函数的color
参数实现。
示例代码:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]
colors = ['red', 'green', 'blue', 'yellow']
plt.bar(x, y, color = colors)
plt.show()
关键参数:color
,可以传入单个颜色值(所有柱子同色),也可传入颜色值列表(每个柱子对应一种颜色)。
Seaborn
Seaborn设置柱状图柱子颜色通常在barplot
函数中通过palette
参数实现。
示例代码:
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
data = {'category': ['A', 'B', 'C', 'D'], 'value': [10, 20, 15, 25]}
df = pd.DataFrame(data)
sns.barplot(x = 'category', y = 'value', data = df, palette='Set1')
plt.show()
关键参数:palette
,用于指定调色板名称,不同调色板有不同颜色组合;若想每个柱子单独指定颜色,也可自定义调色板传入。