![](/img/trans.png)
[英]How to plot a vertical line on a bar plot with a datetime label with only discreet x-axis tick locations?
[英]How can I set the x-axis tick locations for a bar plot created from a pandas DataFrame?
如果您的x標簽具有數值,那么pandas處理條形圖的x-ticks的方式可能會非常混亂。 我們來看這個例子:
import pandas as pd
import numpy as np
x = np.linspace(0, 1, 21)
y = np.random.rand(21)
s = pd.Series(y, index=x)
ax = s.plot(kind='bar', figsize=(10, 3))
ax.figure.tight_layout()
您可能希望刻度線位置直接對應於x
的值,即0,0.05,0.1,...,1.0。 但是,情況並非如此:
print(ax.get_xticks())
# [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20]
而是pandas根據x
中每個元素的索引設置tick 位置 ,但是然后根據x
的值設置tick 標簽 :
print(' '.join(label.get_text() for label in ax.get_xticklabels()))
# 0.0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5 0.55 0.6 0.65 0.7 0.75 0.8 0.85 0.9 0.95 1.0
因此,直接設置刻度位置(通過使用ax.set_xticks
)或將xticks=
參數傳遞給pd.Series.plot()
將不會產生您期望的效果:
new_ticks = np.linspace(0, 1, 11) # 0.0, 0.1, 0.2, ..., 1.0
ax.set_xticks(new_ticks)
相反,您需要分別更新x-ticks的位置和標簽:
# positions of each tick, relative to the indices of the x-values
ax.set_xticks(np.interp(new_ticks, s.index, np.arange(s.size)))
# labels
ax.set_xticklabels(new_ticks)
在大多數情況下,這種行為實際上很有意義。 對於條形圖,x標簽通常是非數字的(例如,對應於類別的字符串),在這種情況下,不可能使用x
的值來設置刻度位置。 如果不引入另一個參數來指定它們的位置,最合乎邏輯的選擇是使用它們的索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.