两个问题的诀窍是理解Matplotlib中的条形图期望每个序列(G1,G2)的总宽度为“1.0”,计算两边的边距。因此,可能最容易设置边距,然后根据每个系列有多少边距来计算每个栏的宽度。在你的情况下,每个系列有两个小节。
假设您左对齐每个条,而不是像您所做的那样居中对齐它们,此设置将导致在x轴上从0.0到1.0、1.0到2.0等范围的序列。因此,每个系列的确切中心(您希望标签出现的位置)将是0.5、1.5等
我已经清理了你的代码,因为有很多无关的变量。请参阅中的注释。import matplotlib.pyplot as plt
import numpy as np
plt.figure(figsize=(7,7), dpi=300)
groups = [[1.04, 0.96],
[1.69, 4.02]]
group_labels = ["G1", "G2"]
num_items = len(group_labels)
# This needs to be a numpy range for xdata calculations
# to work.
ind = np.arange(num_items)
# Bar graphs expect a total width of "1.0" per group
# Thus, you should make the sum of the two margins
# plus the sum of the width for each entry equal 1.0.
# One way of doing that is shown below. You can make
# The margins smaller if they're still too big.
margin = 0.05
width = (1.-2.*margin)/num_items
s = plt.subplot(1,1,1)
for num, vals in enumerate(groups):
print "plotting: ", vals
# The position of the xdata must be calculated for each of the two data series
xdata = ind+margin+(num*width)
# Removing the "align=center" feature will left align graphs, which is what
# this method of calculating positions assumes
gene_rects = plt.bar(xdata, vals, width)
# You should no longer need to manually set the plot limit since everything
# is scaled to one.
# Also the ticks should be much simpler now that each group of bars extends from
# 0.0 to 1.0, 1.0 to 2.0, and so forth and, thus, are centered at 0.5, 1.5, etc.
s.set_xticks(ind+0.5)
s.set_xticklabels(group_labels)