如何使用Matplotlib绘制X轴按降序排列的直方图?

我有如图所示的图表,这是一幅直方图,其X轴为降序排列,请问如何使用Matplotlib绘制该类图表?
使用Matplotlib绘制X轴降序的直方图
要实现X轴降序的直方图,核心是先对数据的频次(或类别)按降序排序,再绘制并匹配轴标签。以下是具体实现方案:
核心步骤
- 统计数据的类别及对应频次
- 按频次对类别做降序排序
- 基于排序后的结果绘制条形图(针对离散类别的直方图实现形式)
- 同步调整X轴刻度与排序后的类别
离散类别数据的代码示例
import matplotlib.pyplot as plt import numpy as np # 替换为你的实际数据 data = np.random.randint(1, 10, size=50) # 统计唯一值和对应频次 unique_vals, counts = np.unique(data, return_counts=True) # 获取降序排序的索引 sorted_idx = np.argsort(counts)[::-1] sorted_vals = unique_vals[sorted_idx] sorted_counts = counts[sorted_idx] # 绘制降序直方图 plt.bar(sorted_vals, sorted_counts) # 设置X轴刻度为排序后的类别 plt.xticks(sorted_vals) # 添加标注 plt.title('降序直方图') plt.xlabel('类别') plt.ylabel('频次') plt.show()
连续型数据的调整方案
如果处理的是连续数据,需要先分箱统计频次,再对频次降序排序,最后调整X轴区间标签:
import matplotlib.pyplot as plt import numpy as np # 连续型示例数据 data = np.random.normal(50, 10, size=200) # 分箱并统计频次 counts, bins = np.histogram(data, bins=10) # 按频次降序排序 sorted_idx = np.argsort(counts)[::-1] sorted_counts = counts[sorted_idx] sorted_bins = bins[sorted_idx] # 绘制降序直方图 plt.bar(sorted_bins[:-1], sorted_counts, width=np.diff(sorted_bins)) # 设置X轴刻度标签 plt.xticks(sorted_bins[:-1], [f"{b:.1f}" for b in sorted_bins[:-1]]) plt.title('连续数据降序直方图') plt.xlabel('区间') plt.ylabel('频次') plt.show()
内容的提问来源于stack exchange,提问作者Ben Yan
相关产品推荐
相关产品推荐

