箱线图网格
假设我有一些数据。
比如说这是天气数据,记录了每个月的降雨量和温度。为了这个例子,我会随机生成一些数据,像这样:
def rand_weather(n):
month = n%12+1
temp_ind = np.random.randint(0,4)
temp = ["freezing", "cold", "moderate", "hot", "extreme"][temp_ind]
rain = np.random.normal(50 - 4*temp_ind, 25) + np.random.randint(0,20)
return month,rain, temp
data = [rand_weather(n) for n in range(3000)]
rain_record = pd.DataFrame(data, columns=["month", "rainfall", "temp"])
所以这些数据看起来大概是这样的:
month rainfall temp
0 1 78.364133 cold
1 2 54.290201 freezing
2 3 81.341265 cold
3 4 98.980334 hot
... ... ... ...
12 1 66.378066 moderate
13 2 44.264323 moderate
... ... ... ...
我可以像这样画出平均值的小多重图:
avgs = rain_record.groupby(['temp','month']).mean()
avgs.reset_index(inplace=True) #Make the 'temp' and 'month' columns again
import pandas.tools.rplot as rplot
plt.figure(figsize=(12,6), dpi=20)
plt.title=pattern
plot = rplot.RPlot(avgs, y='rainfall', x='month')
plot.add(rplot.TrellisGrid(['temp', '.']))
plot.add(rplot.GeomScatter())
#plot.add(rplot.GeomPoint(size=80.0, alpha=0.5))
t=plot.render(plt.gcf())
我也可以像这样画出每个'temp'
的箱线图(以'cold'为例):
rain_record[rain_record.temp=='cold'].boxplot(by='month')
我可以通过循环每个温度来生成一系列的箱线图。
但是这些图的坐标轴不会像小多重图那样自然对齐。
我想应该可以手动设置matplotlib的坐标轴,
但我不太确定怎么做才好。
1 个回答
10
你可以使用seaborn这个库,特别是里面的factorplot
函数:
import seaborn as sns
sns.set_style("whitegrid")
sns.factorplot("month", "rainfall", row="temp", data=rain_record,
size=2, aspect=5, kind="box", palette="PuBuGn_d")
sns.despine(left=True)