我正在尝试绘制此数据框:
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()
在这里,我想从xticklabel中删除“ 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?
答案 0 :(得分:0)
这应该有效:
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)