Matplotlib堆积的条形图
问题描述:
嗨我对matplotlib相当新,但我想绘制一个堆积的条形图。我的酒吧不是堆叠,而是彼此重叠。Matplotlib堆积的条形图
这是我正在存储数据的字典。
eventsDict = {
'A' : [30.427007371788505, 3.821656050955414],
'B' : [15.308879925288613, 25.477707006369428],
'C' : [10.846066723627477, 1.910828025477707],
'D' : [0.32586881793073297, 0.6369426751592357],
'E' : [3.110656307747332, 11.464968152866243],
'F' : [8.183480040534901, 1.910828025477707],
'G' : [3.048065650644783, 16.560509554140125],
'H' : [9.950920976811652, 4.45859872611465]
}
我堆积的条形图有两个小节。第一个包含来自列表第一个值的所有数据,第二个包含列表中的所有第二个值。 (名单是在字典中的值)
首先,我的字典转换为一个元组:
allEvents = list(self.eventsDict.items())
这会把字典到此列表:
all Events = [('A', [30.427007371788505, 3.821656050955414]), ('B', [15.308879925288613, 25.477707006369428]), ('C', [10.846066723627477, 1.910828025477707]), ('D', [0.32586881793073297, 0.6369426751592357]), ('E', [3.110656307747332, 11.464968152866243]), ('F', [8.183480040534901, 1.910828025477707]), ('G', [3.048065650644783, 16.560509554140125]), ('H', [9.950920976811652, 4.45859872611465])]
这是我绘制它:
range_vals = np.linspace(0, 2, 3)
mid_vals = (range_vals[0:-1] + range_vals[1:]) * 0.5
colors = ['#DC7633', '#F4D03F', '#52BE80', '#3498DB', '#9B59B6', '#C0392B', '#2471A3', '#566573', '#95A5A6']
x_label = ['All events. %s total events' % (totalEvents), 'Corrected p-value threshold p < %s. %s total events' % (self.pVal, totalAdjusted)]
#Turn the dict to a tuple. That way it is ordered and is subscriptable.
allEvents = list(self.mod_eventsDict.items())
#print (allEvents)
#Use below to index:
#list[x] key - value pairing
#list[x][0] event name (key)
#list[x][1] list of values [val 1(all), val 2(adjusted)]
#Plot the Top bar first
plt.bar(mid_vals, allEvents[0][1], color = colors[0], label = allEvents[0][0])
#Plot the rest
x = 1
for x in range(1, 20):
try:
plt.bar(mid_vals, allEvents[x-1][1], bottom =allEvents[x-1][1], color = colors[x], label = allEvents[x][0])
x = x + 1
except IndexError:
continue
plt.xticks(mid_vals) # for classic style
plt.xticks(mid_vals, x_label) # for classic style
plt.xlabel('values')
plt.ylabel('Count/Fraction')
plt.title('Stacked Bar chart')
plt.legend()
plt.axis([0, 2.5, 0, 1])
plt.show()
这是图形输出。理想情况下,堆叠时它们应该全部加起来为1。我把它们全部做成整体的一小部分,这样两根酒吧的高度就会相同。但是,它们只是相互重叠。另外请注意,堆栈与字典上的名称有不同的标签。
请帮我调试!
答
您需要以不同的方式设置bottom
- 这会告诉matplotlib放置要绘制的小节底部的位置,因此它需要是之前小节的所有高度的总和。
例如,您可以跟踪条的当前高度与列表,像这样:
current_heights = [0] * 20
for x in range(20):
try:
plt.bar(mid_vals, allEvents[x][1], bottom=current_heights[x], color=colors[x], label=allEvents[x][0])
x = x + 1
current_heights[x] += allEvents[x][1] #increment bar height after plotting
except IndexError:
continue
感谢那定了!我跟踪了当前的高度,就像你在for循环中增加它一样。 – Carmelle