我想用条形图可视化2D数据,其中我想显示每个X的总数以及每个X中Y的比率。我的想法是嵌套的条形图。所以我从每个X中的Y的比率开始:
import pandas as pd
import random
import itertools as itoo
import matplotlib.pyplot as plt
random.seed(0)
s=pd.Series([random.randint(1,10) for _ in range(100)],
index=pd.MultiIndex.from_tuples([(x,y) for x,y in itoo.product(range(10), repeat=2)], names=list("xy")))
fig, axes=plt.subplots(10, sharex=True) # no sharey since only ratios important
for x, ax in zip(range(10), reversed(axes)):
sx=s[x]
ax.bar(sx.index, sx, align="center")
ax.set_xticks(range(10))
ax.yaxis.set_ticks([])
ax.set_ylabel(x)
tot=sx.sum()
#plot label `x` and a single hbar(width=tot) right next to plot?;
http://i59.tinypic.com/3478xgx.png
如何在每个条形图右侧为总计添加水平条?
基本上,它看起来像整个条形图集右侧每个X的总计hbar图(它也应该有一个标记的xaxis)。将这些条与相应的条形图对齐非常重要。我还喜欢子图和水平条之间每“行”的标签。我也想让给定的子图(因此条形图)更窄。
答案 0 :(得分:2)
正如其他人所说,使用gridspec
可以为你做到。以下是如何执行此操作的示例:
import pandas as pd
import random
import itertools as itoo
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from numpy import arange,array
random.seed(0)
s=pd.Series([random.randint(1,10) for _ in range(100)],
index=pd.MultiIndex.from_tuples([(x,y) for x,y in itoo.product(range(10), repeat=2)], names=list("xy")))
fig=plt.figure()
fig.subplots_adjust(hspace=0,wspace=0.5)
gs=gridspec.GridSpec(10,8)
axes=[fig.add_subplot(gs[0,:6])]
[axes.append(fig.add_subplot(gs[i,:6],sharex=axes[0])) for i in range(1,10)]
tot=[] # Keep track of totals
for x, ax in zip(range(10), reversed(axes)):
sx=s[x]
ax.bar(sx.index, sx, align="center")
ax.set_xticks(range(10))
ax.yaxis.set_ticks([])
ax.set_ylabel(x)
tot.append(sx.sum())
#plot label `x` and a single hbar(width=tot) right next to plot
axh=fig.add_subplot(gs[:,6:])
axh.barh(arange(10)-0.4,array(tot))
axh.set_yticks(range(10))
axh.set_ylim(-0.5,9.5)
fig.savefig('test.pdf')
以下是输出结果: