You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中绘制直方图时如何保留X轴的重复值?

How to Preserve Duplicate X-axis Values in Matplotlib Bar Chart

Hey there! The issue you're facing happens because when you pass a list of strings to plt.bar() as the x-values, Matplotlib automatically groups identical string labels together—so it treats all the '1's, '2's, etc., as the same category and merges their bars.

To fix this, we need to use numerical positions for each bar first, then manually assign the original Frequency values as the x-axis tick labels. This way, every bar gets its own unique position, and the labels can repeat as needed.

Here's the modified code:

import matplotlib.pyplot as plt
import numpy as np

variableAmount = [16,20,21,10,12,25,9,13,7,6,5,8,4,3,2,1,0]
Frequency = ['1','1','1','2','2','2','4','4','7','11','12','13','62','105','464','1726','14775']

# Create numerical positions for each bar (one for each element in Frequency)
x_positions = np.arange(len(Frequency))

# Plot bars using the numerical positions
plt.bar(x_positions, variableAmount)

# Set the x-axis tick labels to match the original Frequency values
plt.xticks(x_positions, Frequency)

plt.xlabel('Number of Methods')
plt.ylabel('Variables')
plt.show()

What this does:

  • np.arange(len(Frequency)) generates a sequence of numbers from 0 to 16 (since there are 17 elements in your list), giving each bar a unique position on the x-axis.
  • plt.xticks(x_positions, Frequency) maps each numerical position to its corresponding label from the Frequency list, so the x-axis displays every value exactly as it appears in your original list—including duplicates.

Now your bar chart will show three separate bars labeled '1', three labeled '2', two labeled '4', and so on, just as you intended!

内容的提问来源于stack exchange,提问作者منى

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:32:04