[英]How to change xticklables from pandas plot with timedelta x-axis?
我試圖繪制這個數據幀:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'d': [np.timedelta64(5,'h'), np.timedelta64(7,'h')],
'v': [100,200]})
ax = df.set_index('d').plot.bar()
在這里,我想從xticklabels中刪除“days 0”。
這是我的嘗試:
ax = df.set_index('d').plot.bar()
locs, labels = plt.xticks()
for l in labels:
print(l)
# gives
Text(0, 0, '0 days 05:00:00')
Text(0, 0, '0 days 07:00:00')
也,
xlabels = [l for l in ax.get_xticklabels()]
# [Text(0, 0, '0 days 05:00:00'), Text(1, 0, '0 days 07:00:00')]
但是當我嘗試改變時: xlabels[0][2] = str(xlabels[0][2]).lstrip('days 0
')
我收到以下錯誤:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-22-2e745c3160f9> in <module>()
----> 1 lst[0][2]
TypeError: 'Text' object does not support indexing
如何修復錯誤? 或者作為一個整體,如何改變這個情節中的xticklables?
這應該工作:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.pyplot import text as TEXT
df = pd.DataFrame({'d': [np.timedelta64(5,'h'), np.timedelta64(7,'h')],
'v': [100,200]})
ax = df.set_index('d').plot.bar()
xlabels = [l for l in ax.get_xticklabels()]
newlabels = []
for xlabel in xlabels:
x,y = xlabel.get_position();
lbl = xlabel.get_text().lstrip('0 days ');
text = TEXT(x, y, lbl,visible=False);
newlabels.append(text)
ax.set_xticklabels(newlabels)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.