简体   繁体   English

Seaborn Barplot和X轴上的格式化日期

[英]Seaborn Barplot and Formatting Dates on X-Axis

I am currently working on visualizing datasets with Seaborn and Pandas. 我目前正致力于使用Seaborn和Pandas可视化数据集。 I have some time-dependent data that I would like to graph in bar charts. 我有一些时间相关的数据,我想在条形图中绘制图表。

However, I am battling with two issues in Seaborn: 但是,我正在与Seaborn中的两个问题作斗争:

  1. Formatting dates on the x-axis 在x轴上格式化日期
  2. Only showing a handful of dates (as it doesn't make sense to have every day labeled on a 6 month graph) 只显示少数日期(因为在6个月的图表中标记每一天没有意义)

I have found a solution for my issues in normal Matplotlib, which is: 我在普通的Matplotlib中找到了解决我的问题的方法,它是:

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')

However, I already have most of my graphs done in Seaborn, and I would like to stay consistent. 但是,我已经在Seaborn完成了大部分图表,我希望保持一致。 Once I convert the previous code into Seaborn, I lose the ability to format the dates: 一旦我将之前的代码转换为Seaborn,我就失去了格式化日期的能力:

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()

When I run the code, the date format remains unchanged and I can't locate any dates with DateLocator. 当我运行代码时,日期格式保持不变,我找不到DateLocator的任何日期。

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中以类似于Matplotlib和DateLocator和DateFormatter的方式格式化我的X轴日期?

Thanks in advance. 提前致谢。

No, you cannot use seaborn.barplot in conjunction with matplotlib.dates ticking. 不,你不能将seaborn.barplotmatplotlib.dates结合使用。 The reason is that the ticks for seaborn barplots are at integer positions (0,1,..., N-1). 原因是seaborn条形图的刻度位于整数位置(0,1,...,N-1)。 So they cannot be interpreted as dates. 所以他们不能被解释为日期。

You have two options: 您有两种选择:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM