seaborn FacetGrid图中timedata的设置

Kat*_*ova 5 python plot time-series matplotlib seaborn

我想每月绘制数据并每年显示一年的标签.这是数据:

timedates = ['2013-01-01', '2013-02-01', '2013-03-01', '2013-04-01', '2013-05-01', '2013-06-01', '2013-07-01', 
         '2013-08-01', '2013-09-01', '2013-10-01', '2013-11-01', '2013-12-01', '2014-01-01', '2014-02-01', 
         '2014-03-01', '2014-04-01', '2014-05-01', '2014-06-01', '2014-07-01', '2014-08-01', '2014-09-01', 
         '2014-10-01', '2014-11-01', '2014-12-01']

timedates = pd.to_datetime(timedates)

amount = [38870, 42501, 44855, 44504, 41194, 42087, 43687, 42347, 45098, 43783, 47275, 49767, 
      39502, 35951, 47059, 47639, 44236, 40826, 46087, 41462, 38384, 41452, 36811, 37943]

types = ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 
     'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C']

df_x = pd.DataFrame({'timedates': timedates, 'amount': amount, 'types': types})
Run Code Online (Sandbox Code Playgroud)

我发现如何用matplotlib做到这一点

plt.style.use('ggplot')

fig, ax = plt.subplots()
ax.plot_date(df_x.timedates, df_x.amount, 'v-')
ax.xaxis.set_minor_locator(md.MonthLocator()) 
ax.xaxis.set_minor_formatter(md.DateFormatter('%m'))

ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()

ax.xaxis.set_major_locator(md.YearLocator())
ax.xaxis.set_major_formatter(md.DateFormatter('\n\n%Y'))
plt.show()
Run Code Online (Sandbox Code Playgroud)

每月用标签绘制数据

现在我转向seaborn以考虑不同类型的数据.使用seaborn FacetGrid可以使用相同风格的刻度吗?

g = sns.FacetGrid(df_x, hue='types', size=8, aspect=1.5)
g.map(sns.pointplot, 'timedates', 'amount')
plt.show()
Run Code Online (Sandbox Code Playgroud)

Seaborn timedata蜱虫 当我尝试应用刻度格式时 - 它们就会消失.

Nic*_*eli 5

你可以格式化xticks只包含monthyear该的datetime对象,并获得pointplotxticks对应的散点图点的位置.

df['timedates'] = df['timedates'].map(lambda x: x.strftime('%Y-%m'))


def plot(x, y, data=None, label=None, **kwargs):
    sns.pointplot(x, y, data=data, label=label, **kwargs)

g = sns.FacetGrid(df, hue='types', size=8, aspect=1.5)
g.map_dataframe(plot, 'timedates', 'amount')
plt.show()
Run Code Online (Sandbox Code Playgroud)

图片


Kat*_*ova 0

到目前为止,我都是手动完成的。只需按类型分隔线并将它们绘制在一起即可。

改变了这一行

ax.plot_date(df_x.timedates, df_x.amount, 'v-')
Run Code Online (Sandbox Code Playgroud)

分为三条情节线:

types_levels = df_x.types.unique()

for i in types_levels:
    ax.plot_date(df_x[df_x.types==i].timedates, df_x[df_x.types==i].amount, 'v-')

plt.legend(types_levels)
Run Code Online (Sandbox Code Playgroud)

plot_date 上的多行

虽然这不是答案,但我无法使用seaborn FacetGrid的其他优点。