2015-11-04 51 views
2

绘制我只是想知道我怎么能在绘制这种图表和数据的Seaborn与Seaborn

data.csv:

1,2,3 
2007,05,06 
2007,05,06 
2007,05,08 
2007,05,08 
2007,05,12 
2007,05,15 
2007,05,16 
... 

条形图,我想绘制:

enter image description here

如果有人知道,我将不胜感激如何用Seaborn与我的数据来绘制这种条形图。

+1

只需使用内置的[pandas plotting](http://pandas.pydata.org/pandas-docs/stable/visualization.html#bar-plots) – mwaskom

+0

你是在1 =年,2 =月, 3 =价值?或者他们都与时间有关,而你正在计数? – Leb

+0

@Leb 1 =年份,2 =月份(3不是重要的,不包括在条形图中),您可以看到该示例,其中一个基于月份,另一个基于年份。以月份为例,我计算了1月份所有年份的范围 – GeoCom

回答

2

根据您提供的数据,无法创建绘图,因此我制作了一个小样本进行测试。这是很长的,因为你需要操纵数据。主要想法是了解堆积条形图是添加常规条形图。

import pandas as pd 
import io 
import matplotlib.pyplot as plt 
import seaborn as sns 

# sample data - 3rd column ignored 
data = """ 
year,month,count 
2007,05,06 
2007,05,06 
2007,06,08 
2007,06,08 
2008,05,12 
2008,05,15 
2008,06,16 
    """ 
# read data 
df = pd.read_csv(io.StringIO(data), delimiter=',') 

groups = df.groupby(['year','month']) 
plot_data = groups.count() # obtain count of year and month multi-index 

# additive barplot (May and June) 
sns.barplot(x = plot_data.reset_index(level=1).index.unique(), y = plot_data.sum(axis=0, level=1)['count'], data=df , color = "red", ci=None) 
# single bottom plot (in this case May only or "05") 
bottom_plot = sns.barplot(x = plot_data.reset_index(level=1).index.unique(), y = plot_data.reorder_levels(['month','year']).loc[5]['count'], color = "#0000A3") 

bottom_plot.set_ylabel("Count") 
bottom_plot.set_xlabel("Year") 

plt.show() 

enter image description here

的过程可以增加至包括所有12个月,但我不知道一个单一的代码,会做,没有操纵数据。

+0

我得到一个错误“initial_value必须是unicode或None,不是列表” – GeoCom

+0

此代码适用于我在Python 3.5.1上 – TNT

0

随着熊猫,你可以做一个stacked barplot用简单:

df.plot.bar(stacked=True) 

所以你只需要加载或先重塑你的数据有个为列,在今年的指数:

import numpy as np 
import pandas as pd 
import io 
import matplotlib.pyplot as plt 
import seaborn as sns 
# sample data - 3rd column ignored 
data = """ 
1,2,3 
2007,05,06 
2007,05,06 
2007,06,08 
2007,06,08 
2007,05,06 
2007,05,06 
2007,06,08 
2007,06,08 
2007,05,06 
2007,05,06 
2007,06,08 
2007,06,08 
2008,03,12 
2008,09,15 
2008,02,16 
2008,04,12 
2008,05,15 
2008,06,16 
2008,03,12 
2008,08,15 
2008,02,16 
2008,09,12 
2008,05,15 
2008,06,16 
    """ 
# read data 
df = pd.read_csv(io.StringIO(data), delimiter=',',names= ['year','count','ignore'],header=0,index_col='year') 
nyears = len(np.unique(df.index.values)) 
df['month']=np.tile(np.arange(1,13),nyears) 
#df.drop('ignore',1) 
df.pivot(columns='month',values='count').plot.bar(stacked=True) 
plt.show()