python - 绘制多个图形时如何修复 Matplotlib 中的透明度重叠?
问题描述
我有一个函数,它输入一个字符串(我们正在可视化的数据框的名称)并返回两个可视化该数据的直方图。第一个图(左侧)是原始数据,右侧是标准化后的数据(相同,只是使用 matplotlib 参数密度 = True 绘制的)。但正如您所看到的,当图重叠时,这会导致透明度问题。这是我的这个特定情节的代码:
plt.rcParams["figure.figsize"] = [12, 8]
plt.rcParams["figure.autolayout"] = True
ax0_1 = plt.subplot(121)
_,bins,_ = ax0_1.hist(filtered_0,alpha=1,color='b',bins=15,label='All apples')
ax0_1.hist(filtered_1,alpha=0.9,color='gold',bins=bins,label='Less than two apples')
ax0_1.set_title('Condition 0 vs Condition 1: '+'{}'.format(apple_data),fontsize=14)
ax0_1.set_xlabel('{}'.format(apple_data),fontsize=13)
ax0_1.set_ylabel('Frequency',fontsize=13)
ax0_1.grid(axis='y',linewidth=0.4)
ax0_1.tick_params(axis='x',labelsize=13)
ax0_1.tick_params(axis='y',labelsize=13)
ax0_1_norm = plt.subplot(122)
_,bins,_ = ax0_1_norm.hist(filtered_0,alpha=1,color='b',bins=15,label='All apples',density=True)
ax0_1_norm.hist(filtered_1,alpha=0.9,color='gold',bins=bins,label='Less than two apples',density=True)
ax0_1_norm.set_title('Condition 0 vs Condition 1: '+'{} - Normalized'.format(apple_data),fontsize=14)
ax0_1_norm.set_xlabel('{}'.format(apple_data),fontsize=13)
ax0_1_norm.set_ylabel('Frequency',fontsize=13)
ax0_1_norm.legend(bbox_to_anchor=(2, 0.95))
ax0_1_norm.grid(axis='y',linewidth=0.4)
ax0_1_norm.tick_params(axis='x',labelsize=13)
ax0_1_norm.tick_params(axis='y',labelsize=13)
plt.tight_layout(pad=0.5)
plt.show()
任何关于如何使颜色混合得更好的想法都会有所帮助。或者,如果您知道有任何其他组合可以代替,请随时分享。我对颜色的选择并不挑剔。谢谢!
解决方案
我认为通过直方图的形状或透明度的差异来区分它而不是通过颜色将其可视化来更好地强调这样的直方图。我已经从官方参考中编写了一个带有额外重叠的示例。
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(20211021)
N_points = 100000
n_bins = 20
x = np.random.randn(N_points)
y = .4 * x + np.random.randn(100000) + 2
fig, axs = plt.subplots(2, 2, sharey=True, tight_layout=True)
# We can set the number of bins with the `bins` kwarg
axs[0,0].hist(x, color='b', alpha=0.9, bins=n_bins, ec='b', fc='None')
axs[0,0].hist(y, color='gold', alpha=0.6, bins=21)
axs[0,0].set_title('edgecolor and facecolor None')
axs[0,1].hist(x, color='b', alpha=0.9, bins=n_bins)
axs[0,1].hist(y, color='gold', alpha=0.6, bins=21, ec='b')
axs[0,1].set_title('edgecolor and facecolor')
axs[1,0].hist(x, alpha=0.9, bins=n_bins, histtype='step', facecolor='b')
axs[1,0].hist(y, color='gold', alpha=0.6, bins=21)
axs[1,0].set_title('step')
axs[1,1].hist(x, color='b', alpha=0.9, bins=n_bins, histtype='bar', rwidth=0.8)
axs[1,1].hist(y, color='gold', alpha=0.6, bins=21, ec='b')
axs[1,1].set_title('bar')
plt.show()
推荐阅读
- python - 如何将多个函数的输出重定向到 python 中的字符串或标准输出?(标准输出与变量的相反)
- python - 用 groupby 平均值替换 pandas 数据框的空值
- node.js - app.use() 需要中间件函数错误
- xslt - XSLT, XPath, 使用 current() 的值进行选择和求和
- typescript - 如何判断一个值是否已设置为未定义或根本没有设置?
- react-native - 尝试运行 react native、expo、vs code、android studio 的主要问题
- r - 在 ggplot2 的第二个系列中绘制错误
- node.js - 在构建时从 url 预加载/保存图像
- spring-boot - Java 模型休眠映射问题
- java - JavaFX - 遍历 GridPane 中的文本字段并暂停更新文本