0

我想以这样的方式绘制我的数据,将条形分组?像这样:

例子

到目前为止,我的代码如下所示:

data = NP.genfromtxt('newfile',unpack=True,names=True,dtype=None)
for i in sample:
 mask = data['name'==sample]
 ax2.bar(pos-0.5,(data['data']*100,label="samples", color="lightblue")

不过,这创建了几个图表,而不是一个组合图表。我如何将其转换为看起来像我上面介绍的图形?

4

1 回答 1

2

在没有列出所有代码的情况下,我不得不对数据和你想要的东西做出一些假设。因此,我没有用实际数据测试过这段代码。我试图在下面的代码中仔细记录我的假设。如果您对我发布的内容有疑问,也许您可​​以发布代码第一行中提到的文本文件。

# Assume data is a record array
data = NP.genfromtxt('newfile',unpack=True,names=True,dtype=None)

# Assume 'sample' is a column in the data
sample = NP.unique(data['name'])
num_items = len(sample)
ind = NP.arange(sample)

# The margin can be increased to add more space between the groups of data
margin = 0.05
width = (1.-2.*margin)/num_items

# This list will make each sample data set a different color
# It must be AT LEAST as long as the number of samples
# If not, the extra data won't be plotted
colorList = ['red', 'blue', 'black']
if len(colorList) < num_items:
    print 'Warning: the number of samples exceeds the length of the color list.'

f = plt.figure()

# Assumed the color was supposed to vary with each data set, so I added a list
for s, color in zip(enumerate(sample), colorList):
    num, i = s
    print "plotting: ", i
    # Assumed you want to plot a separate set of bars for each sample, so I changed the mask to 'name'==i
    mask = data['name'==i]
    # The position of the xdata must be calculated for each of the sample data series
    xdata = ind+margin+(num*width)
    # Assumed you wanted to plot the 'data' column where mask is true and then multiply by 100
    # Also assumed the label and color were supposed to vary with each data set
    plt.bar(xdata, data['data'][mask]*100, width, label=i, color=color)
于 2012-09-18T15:58:16.200 回答