我使用pylab创建了以下条形图
对于每个条形图,是否有指定颜色的方法?以下是我的代码
import numpy as np
import matplotlib.pyplot as plt
month = ["dec-09", "jan", "feb"]
n = len(month)
air = np.array([383.909, 395.913, 411.714])
ind = np.arange(n)
width = 0.35
print(n)
print(ind)
plt.bar(ind, air, width, color="yellow")
plt.ylabel("KWH")
plt.title("winter")
plt.xticks(ind+width/2, ("dec-09", "jan", "feb"))
plt.show()
答案 0 :(得分:0)
是。 plt.bar
的文档字符串说:
Make a bar plot.
Make a bar plot with rectangles bounded by:
`left`, `left` + `width`, `bottom`, `bottom` + `height`
(left, right, bottom and top edges)
Parameters
----------
left : sequence of scalars
the x coordinates of the left sides of the bars
[snip]
color : scalar or array-like, optional
the colors of the bar faces
因此,您可以将颜色列表传递给plt.bar
,它会分别为每个条形图着色。
所以你的例子变成了:
import numpy as np
import matplotlib.pyplot as plt
month = ["dec-09", "jan", "feb"]
n = len(month)
air = np.array([383.909, 395.913, 411.714])
ind = np.arange(n)
width = 0.35
fig, ax = plt.subplots()
ax.bar(ind, air, width, color=["yellow", 'cornflowerblue', 'darkgreen'])
ax.set_ylabel("KWH")
ax.set_title("winter")
ax.set_xticks(ind+width/2)
ax.set_xticklabels(("dec-09", "jan", "feb"))