Seaborn 条形图和 X 轴上的格式化日期

问题描述:

我目前正在使用 Seaborn 和 Pandas 对数据集进行可视化.我有一些与时间相关的数据,我想用条形图绘制它们.

I am currently working on visualizing datasets with Seaborn and Pandas. I have some time-dependent data that I would like to graph in bar charts.

但是,我在 Seaborn 中遇到了两个问题:

However, I am battling with two issues in Seaborn:

  1. 在 x 轴上格式化日期
  2. 只显示少数日期(如在 6 个月的图表上标注每一天是没有意义的)

我在普通 Matplotlib 中找到了解决我的问题的方法,即:

I have found a solution for my issues in normal Matplotlib, which is:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

dates = pandas.date_range('1/1/2014', periods=20, freq='m')
df = pandas.DataFrame(
    data={'dt':dates, 'val':numpy.random.randn(N)}
)

fig, ax = plt.subplots(figsize=(10, 6))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
ax.bar(df['dt'], df['val'], width=25, align='center')

但是,我已经在 Seaborn 中完成了大部分图表,我希望保持一致.一旦我将之前的代码转换成 Seaborn,我就失去了格式化日期的能力:

However, I already have most of my graphs done in Seaborn, and I would like to stay consistent. Once I convert the previous code into Seaborn, I lose the ability to format the dates:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

dates = pandas.date_range('1/1/2014', periods=20, freq='m')
df = pandas.DataFrame(
    data={'dt':dates, 'val':numpy.random.randn(N)}
)

fig, ax = plt.subplots(1,1)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%y-%m'))
sns.barplot(x='dt', y='val', data=df)
fig.autofmt_xdate()

当我运行代码时,日期格式保持不变,我无法使用 DateLocator 定位任何日期.

When I run the code, the date format remains unchanged and I can't locate any dates with DateLocator.

有什么方法可以让我在 Seaborn 中以类似于 Matplotlib 的方式使用 DateLocator 和 DateFormatter 格式化我的 X 轴日期?

Is there any way for me to format my X-Axis for dates in Seaborn in a way similar to Matplotlib with DateLocator and DateFormatter?

提前致谢.

不,您不能将 seaborn.barplotmatplotlib.dates 打勾一起使用.原因是 seaborn 条形图的刻度位于整数位置 (0,1,..., N-1).所以它们不能被解释为日期.

No, you cannot use seaborn.barplot in conjunction with matplotlib.dates ticking. The reason is that the ticks for seaborn barplots are at integer positions (0,1,..., N-1). So they cannot be interpreted as dates.

您有两个选择:

  1. 使用 seaborn,遍历标签并将它们设置为您想要的任何内容
  2. 不使用 seaborn 并具有可用的 matplotlib.dates 代码的优点(和缺点).
  1. Use seaborn, and loop through the labels and set them to anything you want
  2. Not use seaborn and have the advantages (and disadvantages) of matplotlib.dates tickers available.