【发布时间】:2015-10-26 22:03:39
【问题描述】:
我正在构建一个 Seaborn 条形图。 x 轴是日期,y 轴是整数。
我想格式化日期的主要/次要刻度。我希望星期一的刻度加粗并使用不同的颜色(即“主要刻度”),而一周的其余时间不那么粗体。
我无法在 x 轴上获得主要和次要刻度格式以用于 Seaborn 条形图。我被难住了,因此转向这里寻求帮助。
我从回答这个问题的 stackoverflow 示例开始:Pandas timeseries plot setting x-axis major and minor ticks and labels
如果我对其进行简单修改以使用 Seaborn 条形图,我会丢失 X 轴刻度:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
import seaborn as sns
idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)
###########################################
## Swap out these two lines of code:
#fig, ax = plt.subplots()
#ax.plot_date(idx.to_pydatetime(), s, 'v-')
## with this one
ax = sns.barplot(idx.to_pydatetime(), s)
###########################################
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
## save the result to a png instead of plotting to screen:
myFigure = plt.gcf()
myFigure.autofmt_xdate()
myFigure.set_size_inches(11,3.8)
plt.title('Example Chart', loc='center')
plt.savefig('/tmp/chartexample.png', format='png', bbox_inches='tight')
我尝试了多种方法,但 Seaborn 中的某些东西似乎覆盖或撤销了我设法为 all设置一些简单样式的长轴和短轴格式的任何尝试> 当我使用set_xticklabels() 时打勾。
我可以使用MultipleLocator() 对主要刻度进行格式化,但我无法对次要刻度进行任何格式化。
我还尝试了myFigure.autofmt_xdate() 看看它是否会有所帮助,但它似乎也不喜欢在同一轴上混合主要和次要刻度。
【问题讨论】:
标签: python datetime matplotlib seaborn