python - 当 bin 不等间距时,如何在 matplotlib 直方图中的 xaxis 中创建等间距间隔?
问题描述
我希望 matplotlib 直方图以等间距的 xaxis 显示数据,尽管其 bin 的值不是等间距的。我该怎么做?目前,年龄组“0-6”、“7-12”、“13-16”、“17-20”的条形看起来比我的其他数据更薄,“17-20”的条形与 21- 重叠30. xticklabels 也是重叠的。我该如何解决这些问题?
#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
male_ages = [66.0, 37.0, 2.0, 56.0, 8.0, 56.0, 56.0, 31.0, 15.0, 41.0, 17.0, 40.0, 45.0, 0.5, 41.0, 27.0, 53.0, 64.0, 53.0,]
female_ages = [53.0, 56.0, 3.0, 31.0, 9.0, 73.0, 47.0, 18.0, 31.0, 28.0, 48.0, 44.0, 32.0, 42.0, 42.0, 39.0, 40.0, 38.0, 2.0 ]
age_bins_label = [ '0-6', '7-12', '13-16', '17-20', '21-30',
'31-40', '41-50', '51-60', '61-70', '71-80',
'81-90', '91-100', '101-110', '111-120' ]
age_bins = [0, 6, 12, 16, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110 ]
xmax = max( male_ages, female_ages)
data = [ male_ages, female_ages ]
colors = [ 'orange', 'pink']
labels = [ 'male', 'female' ]
fig, axs = plt.subplots(2, 2, 'all', tight_layout=True, sharey=True )
axs[0, 0].hist( data, bins=age_bins, color=colors, rwidth=0.9, align='left',
stacked=False, label=labels )
axs[0, 0].legend(prop={'size': 10})
axs[0, 0].set_title('bars with legend')
axs[0, 0].get_xaxis().set_label_text( label='Age Groups', fontweight='bold' )
axs[0, 0].get_yaxis().set_label_text( label='Confirmed Cases', fontweight='bold' )
for ax in axs.flat:
ax.label_outer()
# Set x-axis
#xlabels = [ str(i) for i in age_bins[1:] ]
xlabels = age_bins_label
N_labels = len(xlabels)
plt.xticks( age_bins, xlabels )
plt.show()
解决方案
我建议你利用np.histogram
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
male_ages = [66.0, 37.0, 2.0, 56.0, 8.0, 56.0, 56.0, 31.0, 15.0, 41.0, 17.0, 40.0, 45.0, 0.5, 41.0, 27.0, 53.0, 64.0, 53.0,]
female_ages = [53.0, 56.0, 3.0, 31.0, 9.0, 73.0, 47.0, 18.0, 31.0, 28.0, 48.0, 44.0, 32.0, 42.0, 42.0, 39.0, 40.0, 38.0, 2.0 ]
age_bins_label = [ '0-6', '7-12', '13-16', '17-20', '21-30',
'31-40', '41-50', '51-60', '61-70', '71-80',
'81-90', '91-100', '101-110', '111-120' ]
age_bins = [0, 6, 12, 16, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120 ]
fig, ax = plt.subplots()
ax.bar(x = age_bins_label,
height = np.histogram(male_ages, bins = age_bins)[0],
alpha=0.5,
label='male')
ax.bar(x = age_bins_label,
height = np.histogram(female_ages, bins = age_bins)[0],
alpha=0.5,
label='female')
plt.legend(loc='upper right')
推荐阅读
- python - 如何让 VSCode 的终端识别 python
- ethereum - 警告:函数状态的可变性可以限制为纯函数
- visual-studio-code - vscode 用诗歌测试发现(src 布局)
- python - 在一列上进行复杂转换,同时在 Python/Pandas 中保留原始列
- windows - 如何将 EXE 构建部署到 Amazon Web Service?
- javascript - 如何为哈希表查找键实现基于 3 位的哈希函数?
- python - 锁定线程并创建新游标无法解决 sqlite3“不允许递归使用游标”
- reactjs - React 应用程序的结构可以隐藏在登录后面吗?
- flutter - 在 Flutter 的磁贴中有条件地显示/隐藏复选框
- function - Delphi函数将枚举转换为字符串列表......?