为直方图中的每个 bin 绘制不同的颜色 (Matplotlib)
Plotting a different color for each bin in a histogram (Matplotlib)
我有一个这样的 pandas 数据框:
Favorite B | Q1
________________
McDonalds | 5
BurgerKing | 6
KFC | 3
Brand4 | 2
我正在绘制直方图:
x=pd.Series(df["Q1"])
result = plt.hist(x, bins=7, color='c', edgecolor='k', alpha=0.65)
plt.axvline(x.mean(), color='k', linestyle='dashed', linewidth=1)
min_ylim, max_ylim = plt.ylim()
plt.text(x.mean()*1.1, max_ylim*0.9, 'Mean: {:.2f}'.format(x.mean()))
plt.title(str(i))
我想要每个箱子的颜色不同。
我该怎么做?
这应该有效(基于 this example):
import numpy as np
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(0)
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
n, bins, patches = plt.hist(x, bins=len(colors))
# adapt the color of each patch
for c, p in zip(colors, patches):
p.set_facecolor(c)
plt.show()
我有一个这样的 pandas 数据框:
Favorite B | Q1
________________
McDonalds | 5
BurgerKing | 6
KFC | 3
Brand4 | 2
我正在绘制直方图:
x=pd.Series(df["Q1"])
result = plt.hist(x, bins=7, color='c', edgecolor='k', alpha=0.65)
plt.axvline(x.mean(), color='k', linestyle='dashed', linewidth=1)
min_ylim, max_ylim = plt.ylim()
plt.text(x.mean()*1.1, max_ylim*0.9, 'Mean: {:.2f}'.format(x.mean()))
plt.title(str(i))
我想要每个箱子的颜色不同。 我该怎么做?
这应该有效(基于 this example):
import numpy as np
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(0)
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
n, bins, patches = plt.hist(x, bins=len(colors))
# adapt the color of each patch
for c, p in zip(colors, patches):
p.set_facecolor(c)
plt.show()