如何在 matplotlib 中通过彩虹设置箱线图颜色
How can I set boxplot color by rainbow in matplotlib
我想在比较中创建数据箱线图,我的图看起来像
我怎样才能像这样添加颜色
您可以为 this example. Beyond that, you will need to map your data in mind to color on the "rainbow" colormap with this module 之后的框着色。这是一个随机测试数据的例子。在此示例中,我使用均值映射颜色。
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
# Random test data
test_data = [np.random.normal(mean, 1, 100) for mean in range(50)]
fig, axes = plt.subplots(figsize=(12, 16))
# Horizontal box plot
bplot = axes.boxplot(test_data,
vert=False, # vertical box aligmnent
patch_artist=True) # fill with color
# Fill with colors
cmap = cm.ScalarMappable(cmap='rainbow')
test_mean = [np.mean(x) for x in test_data]
for patch, color in zip(bplot['boxes'], cmap.to_rgba(test_mean)):
patch.set_facecolor(color)
plt.show()
您可以使用 cmap
属性 实际上是一个函数,接受 0 到 1 之间的值,并将其称为 "normalising" 您的数据。在箱线图上使用 matplotlib
示例:
import matplotlib.pyplot as plt
import numpy as np
# Random test data
np.random.seed(123)
all_data = [np.random.normal(0, 5, 100) for std in range(1, 21)]
fig, ax = plt.subplots(nrows=1, figsize=(9, 4))
# rectangular box plot
bplot = ax.boxplot(all_data, 0, '', 0, patch_artist=True)
cm = plt.cm.get_cmap('rainbow')
colors = [cm(val/len(all_data)) for val in range(len(all_data))]
for patch, color in zip(bplot['boxes'], colors):
patch.set_facecolor(color)
plt.show()
我想在比较中创建数据箱线图,我的图看起来像
我怎样才能像这样添加颜色
您可以为 this example. Beyond that, you will need to map your data in mind to color on the "rainbow" colormap with this module 之后的框着色。这是一个随机测试数据的例子。在此示例中,我使用均值映射颜色。
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
# Random test data
test_data = [np.random.normal(mean, 1, 100) for mean in range(50)]
fig, axes = plt.subplots(figsize=(12, 16))
# Horizontal box plot
bplot = axes.boxplot(test_data,
vert=False, # vertical box aligmnent
patch_artist=True) # fill with color
# Fill with colors
cmap = cm.ScalarMappable(cmap='rainbow')
test_mean = [np.mean(x) for x in test_data]
for patch, color in zip(bplot['boxes'], cmap.to_rgba(test_mean)):
patch.set_facecolor(color)
plt.show()
您可以使用 cmap
属性 实际上是一个函数,接受 0 到 1 之间的值,并将其称为 "normalising" 您的数据。在箱线图上使用 matplotlib
示例:
import matplotlib.pyplot as plt
import numpy as np
# Random test data
np.random.seed(123)
all_data = [np.random.normal(0, 5, 100) for std in range(1, 21)]
fig, ax = plt.subplots(nrows=1, figsize=(9, 4))
# rectangular box plot
bplot = ax.boxplot(all_data, 0, '', 0, patch_artist=True)
cm = plt.cm.get_cmap('rainbow')
colors = [cm(val/len(all_data)) for val in range(len(all_data))]
for patch, color in zip(bplot['boxes'], colors):
patch.set_facecolor(color)
plt.show()