2016-08-24 132 views
3

我想每月绘制数据,并且每年显示一次年度标签。 这里是数据:在seaborn FacetGrid地块中设置时间数据

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

我发现了如何做到这一点与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() 

Plot data monthly with labels

现在我搬到seaborn考虑到不同类型的数据。使用seaborn FacetGrid可以使用相同样式的蜱吗?

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

Seaborn timedata ticks 当我尝试申请蜱格式 - 他们只是消失。

+1

你看到这个http://stackoverflow.com/questions/31810316/seaborn-matplotlib-date-axis-barplot-minor-major-tick-formatting和https:// github上.COM/mwaskom/seaborn /问题/ 498。听起来像Pandas/Seaborne和matplotlib之间的标签和日期之间的不兼容。你可以使用'g.ax.set_xticks([日期,格式,你想要的])手动解决...... –

+0

@EdSmith是的,我看到第一个链接,但没有答案。并感谢第二个和代码,我会检查是否有可能做到。 –

回答

0

到目前为止,我手动做了。按照类型分开线条并将它们绘制在一起。

改变了这一行

ax.plot_date(df_x.timedates, df_x.amount, 'v-') 

分为三个情节线:

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) 

Multiple lines on plot_date

虽然它不是一个答案,我无法用seaborn FacetGrid等优点。

4

你可以格式化xticks只包括datetime对象的monthyear并获得与xticks一个pointplot对应的散点图点的位置。

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

Image

+1

非常感谢!这不是我最初想要的,但它可以是一个解决方案!如果没有太多的数据周期:) –

+0

另外,如果你想使用'pandas'绘制大数据集,你可以使用'x_compat = True'来抑制'xticks'的重叠行为。 –

相关问题