我正在尝试从pandas
DataFrame列'Time'
绘制直方图,该列每天都有主要的刻度线,每小时有一个较小的刻度线,并且两个标签都有不同的“偏移”。
到目前为止,我拥有的是
import datetime
import random
import dateutil.parser
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
start = dateutil.parser.parse("1 January 2019")
end = dateutil.parser.parse("3 January 2019")
data = [start + (end - start) * random.random() for _ in range(1000)]
df = pd.DataFrame(data, columns=['Time'])
fig, ax = plt.subplots(1, 1)
ax.hist(df['Time'], bins=mdates.drange(start, end, datetime.timedelta(hours=1)))
ax.xaxis.set_major_locator(mdates.DayLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%y'))
ax.xaxis.set_minor_locator(mdates.HourLocator())
ax.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M'))
ax.xaxis.grid(True, which='minor')
ax.yaxis.grid(True)
ax.set_ylabel('Counts per hour')
fig.autofmt_xdate()
plt.tight_layout()
plt.show()
这会导致在x轴上具有重叠标签的图:
我相信我可以通过每3小时使用RRuleLocator
而不是HourLocator
来增加小时刻度之间的间隔。但是,如何防止每天午夜的小时标签与当天的日期标签重叠?有没有办法垂直偏移这两套标签?
答案 0 :(得分:1)
这当然只是许多可能的选项之一:我会将fontsize的顺序的填充设置为主要的ticklabels。
ax.tick_params(axis="x", which="major", pad=12)
完整代码:
import datetime
import random
import dateutil.parser
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
start = dateutil.parser.parse("1 January 2019")
end = dateutil.parser.parse("3 January 2019")
data = [start + (end - start) * random.random() for _ in range(1000)]
df = pd.DataFrame(data, columns=['Time'])
fig, ax = plt.subplots(1, 1)
ax.hist(df['Time'], bins=mdates.drange(start, end, datetime.timedelta(hours=1)))
ax.xaxis.set_major_locator(mdates.DayLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%y'))
ax.xaxis.set_minor_locator(mdates.HourLocator((0,6,12,18,)))
ax.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M'))
ax.xaxis.grid(True, which='minor')
ax.yaxis.grid(True)
ax.set_ylabel('Counts per hour')
ax.tick_params(axis="x", which="major", pad=12)
plt.tight_layout()
plt.show()