如果您为直方图中的每个条创建一个包含颜色的列表,您可以使用以下代码 sn-p。它捕获plt.hist 命令的返回值,其中包括各个补丁。可以在迭代这些补丁时单独设置颜色。
n, bins, patches = plt.hist(var1, bins=8, range=(0,4000), color="orange", alpha=0.7)
for i, patch in enumerate(patches):
plt.setp(patch, "facecolor", colors[i])
此外,根据您拥有的数据类型,这是创建上述color list 的一种可能方法:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# create random values and store them in a DataFrame
y1 = np.random.randint(0,4000, 50)
y2 = np.random.randint(-100, 101, 50)
y = zip(y1,y2)
df = pd.DataFrame(y, columns=["Var1","Var2"])
var1 = df["Var1"].values
# pd.cut to bin the dataframe in the appropriate ranges of Var1
# then the mean of Var2 is calculated for each bin, results are stored in a list
mean = [df.groupby(pd.cut(df["Var1"], np.arange(0, 4000+500, 500)))["Var2"].mean()]
# how to color the bars based on Var2:
# -100 <= mean(Var2) < -33: blue
# -33 <= mean(Var2) < 33: red
# 33 <= mean(Var2) < 100: green
color_bins = np.array([-100,-33,33,100])
color_list = ["blue","red","green"]
# bin the means of Var2 according to the color_bins we just created
inds = np.digitize(mean, color_bins)
# list that assigns the appropriate color to each patch
colors = [color_list[value-1] for value in inds[0]]
n, bins, patches = plt.hist(var1, bins=8, range=(0,4000), color="orange", alpha=0.7)
for i, patch in enumerate(patches):
plt.setp(patch, "facecolor", colors[i])
plt.title('Var 1',weight='bold', fontsize=18)
plt.yticks(weight='bold')
plt.xticks(weight='bold')
plt.show()