簡體   English   中英

是否可以將 x 軸刻度與 matplotlib 直方圖中的相應條對齊?

[英]Is it possible to align x-axis ticks with corresponding bars in a matplotlib histogram?

在繪制時間序列日期時,我正在嘗試 plot 每小時的數據點數:

fig, ax = plt.subplots()
ax.hist(x = df.index.hour,
        bins = 24,         # draw one bar per hour 
        align = 'mid'      # this is where i need help
        rwidth = 0.6,      # adding a bit of space between each bar
        )

我想要每小時一個酒吧,每個小時都有標簽,所以我們設置:

ax.set_xticks(ticks = np.arange(0, 24))
ax.set_xticklabels(labels = [str(x) for x in np.arange(0, 24)])

x 軸刻度正確顯示和標記,但條形本身未正確對齊刻度上方。 條形圖更靠近中心,將它們設置在左側刻度線的右側,而右側刻度線的左側。

align = 'mid'選項允許我們將 xticks 移動到'left' / 'right' ,但這些都不能幫助解決手頭的問題。

未對齊的條形圖

有沒有辦法將條形設置在直方圖中相應刻度的正上方?

為了不跳過細節,這里設置了一些參數,以便通過 imgur 的黑色背景獲得更好的可見性

fig.patch.set_facecolor('xkcd:mint green')
ax.set_xlabel('hour of the day')
ax.set_ylim(0, 800)
ax.grid()
plt.show()

當您放置bins=24時,您不會每小時獲得一個垃圾箱。 假設您的小時數是從 0 到 23 的整數, bins=24將創建 24 個 bin,將 0.0 到 23.0 的范圍分成 24 個相等的部分。 因此,區域將是0-0.9580.958-1.9171.917-2.75 、 ... 22.042-23 如果值不包含023 ,則會發生更奇怪的事情,因為將在遇到的最低值和最高值之間創建范圍。

由於您的數據是離散的,因此強烈建議顯式設置 bin 邊緣。 例如數字-0.5 - 0.5 , 0.5 - 1.5 , ... 。

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.hist(x=np.random.randint(0, 24, 500),
        bins=np.arange(-0.5, 24),  # one bin per hour
        rwidth=0.6,  # adding a bit of space between each bar
        )
ax.set_xticks(ticks=np.arange(0, 24)) # the default tick labels will be these same numbers
ax.margins(x=0.02) # less padding left and right
plt.show()

示例圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM