根据分布的广泛程度改变 matplotlib 中小提琴图的颜色
Change color of violin plot in matplotlib according to how broad the distribution is
我一直在尝试使用 Python 中的 Matplotlib 库绘制一个漂亮的小提琴图来展示我的数据。这是我使用的代码:
ax.violinplot(vdistances,showmeans=False,showmedians=True)
ax.set_title('Distance analysis for molecule 1')
ax.set_xlabel('Atomic distances')
ax.set_ylabel('Distances in Amstrongs')
ax.set_xticks([x for x in range(1,len(distances)+1)])
plt.show()
这就是我想出的:
我一直在想的是,是否可以根据分布的广泛程度,将相同颜色的不同音调分配给每把小提琴,因此数据越分散。
您可以遍历生成的小提琴,提取它们的高度并使用它来设置颜色:
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
from matplotlib.cm import ScalarMappable
import numpy as np
fig, ax = plt.subplots(figsize=(12, 5))
vdistances = np.random.normal(np.random.uniform(10, 20, (20, 10)), np.random.uniform(2, 5, (20, 10)))
violins = ax.violinplot(vdistances, showmeans=False, showmedians=True)
ax.xaxis.set_major_locator(MultipleLocator(1))
heights = [violin.get_paths()[0].get_extents().height for violin in violins['bodies']]
norm = plt.Normalize(min(heights), max(heights))
cmap = plt.get_cmap('plasma')
for violin, height in zip(violins['bodies'], heights):
violin.set_color(cmap(norm(height)))
violin.set_alpha(0.5)
plt.colorbar(ScalarMappable(norm=norm, cmap=cmap), alpha=violin.get_alpha(), label='Violin Extent', ax=ax)
plt.tight_layout()
plt.show()
我一直在尝试使用 Python 中的 Matplotlib 库绘制一个漂亮的小提琴图来展示我的数据。这是我使用的代码:
ax.violinplot(vdistances,showmeans=False,showmedians=True)
ax.set_title('Distance analysis for molecule 1')
ax.set_xlabel('Atomic distances')
ax.set_ylabel('Distances in Amstrongs')
ax.set_xticks([x for x in range(1,len(distances)+1)])
plt.show()
这就是我想出的:
我一直在想的是,是否可以根据分布的广泛程度,将相同颜色的不同音调分配给每把小提琴,因此数据越分散。
您可以遍历生成的小提琴,提取它们的高度并使用它来设置颜色:
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
from matplotlib.cm import ScalarMappable
import numpy as np
fig, ax = plt.subplots(figsize=(12, 5))
vdistances = np.random.normal(np.random.uniform(10, 20, (20, 10)), np.random.uniform(2, 5, (20, 10)))
violins = ax.violinplot(vdistances, showmeans=False, showmedians=True)
ax.xaxis.set_major_locator(MultipleLocator(1))
heights = [violin.get_paths()[0].get_extents().height for violin in violins['bodies']]
norm = plt.Normalize(min(heights), max(heights))
cmap = plt.get_cmap('plasma')
for violin, height in zip(violins['bodies'], heights):
violin.set_color(cmap(norm(height)))
violin.set_alpha(0.5)
plt.colorbar(ScalarMappable(norm=norm, cmap=cmap), alpha=violin.get_alpha(), label='Violin Extent', ax=ax)
plt.tight_layout()
plt.show()