具有超过 7 个数据集的 Pyplot 直方图
Pyplot historgram with more than 7 datasets
Pyplot 可让您创建多个数据集的堆叠直方图(如 this one)。
但是,如果我在直方图中有超过 7 个数据集,它会重复颜色。
有没有办法区分超过 7 种不同的颜色?
我尝试使用可选的影线参数 (documented here),但它只对所有条形图采用一种影线样式,而不是对每个条形图采用一种影线样式。
# This applies one hatch-style to all bars
plt.hist(data, label=label, normed=True, stacked=True, hatch='/')
# This doesn't apply different hatch styles to different bars.
# It throws an error
plt.hist(data, label=label, normed=True, stacked=True, hatch=
['/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*', 'oo', 'xx'])
Matplotlib 使用具有预定义颜色的颜色循环。您可以根据自己的喜好修改此颜色循环,但如果您直接在对 hist
的调用中指定颜色,它会更清晰。手动指定颜色很繁琐,因此您可以使用 matplotlibs 颜色映射之一来生成它们。在下面的示例中,我还使用了 colorbrewer 的颜色图,因为它们也很不错。
import matplotlib.pyplot as plt
import numpy as np
import brewer2mpl
colors_brewer = brewer2mpl.get_map('Paired', 'Qualitative', 12).mpl_colors
colors_jet = plt.cm.jet(np.linspace(0,1,12))
# random data
data = np.random.rand(100,12)
# plot it
fig, ax = plt.subplots(1,2)
ax[0].hist(data, bins=10, stacked=True, color=colors_brewer)
ax[1].hist(data, bins=10, stacked=True, color=colors_jet)
plt.show()
结果:
Pyplot 可让您创建多个数据集的堆叠直方图(如 this one)。
但是,如果我在直方图中有超过 7 个数据集,它会重复颜色。
有没有办法区分超过 7 种不同的颜色?
我尝试使用可选的影线参数 (documented here),但它只对所有条形图采用一种影线样式,而不是对每个条形图采用一种影线样式。
# This applies one hatch-style to all bars
plt.hist(data, label=label, normed=True, stacked=True, hatch='/')
# This doesn't apply different hatch styles to different bars.
# It throws an error
plt.hist(data, label=label, normed=True, stacked=True, hatch=
['/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*', 'oo', 'xx'])
Matplotlib 使用具有预定义颜色的颜色循环。您可以根据自己的喜好修改此颜色循环,但如果您直接在对 hist
的调用中指定颜色,它会更清晰。手动指定颜色很繁琐,因此您可以使用 matplotlibs 颜色映射之一来生成它们。在下面的示例中,我还使用了 colorbrewer 的颜色图,因为它们也很不错。
import matplotlib.pyplot as plt
import numpy as np
import brewer2mpl
colors_brewer = brewer2mpl.get_map('Paired', 'Qualitative', 12).mpl_colors
colors_jet = plt.cm.jet(np.linspace(0,1,12))
# random data
data = np.random.rand(100,12)
# plot it
fig, ax = plt.subplots(1,2)
ax[0].hist(data, bins=10, stacked=True, color=colors_brewer)
ax[1].hist(data, bins=10, stacked=True, color=colors_jet)
plt.show()
结果: