-
Notifications
You must be signed in to change notification settings - Fork 21
/
stackedBarGraph.py
executable file
·291 lines (251 loc) · 11.6 KB
/
stackedBarGraph.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
#!/usr/bin/env python
###############################################################################
# #
# stackedBarGraph.py - code for creating purdy stacked bar graphs #
# #
###############################################################################
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
# #
###############################################################################
__author__ = "Michael Imelfort"
__copyright__ = "Copyright 2014-2017"
__license__ = "GPL3"
__version__ = "1.0"
###############################################################################
import numpy as np
from matplotlib import pyplot as plt
###############################################################################
class StackedBarGrapher:
"""Container class"""
def __init__(self): pass
def demo(self):
d = np.array([[101.,0.,0.,0.,0.,0.,0.],
[92.,3.,0.,4.,5.,6.,0.],
[56.,7.,8.,9.,23.,4.,5.],
[81.,2.,4.,5.,32.,33.,4.],
[0.,45.,2.,3.,45.,67.,8.],
[99.,5.,0.,0.,0.,43.,56.]])
d_heights = [1.,2.,3.,4.,5.,6.]
d_widths = [.5,1.,3.,2.,1.,2.]
d_labels = ["fred","julie","sam","peter","rob","baz"]
d_colors = ['#2166ac', '#fee090', '#fdbb84', '#fc8d59', '#e34a33', '#b30000', '#777777']
gap = 0.05
fig = plt.figure()
ax1 = fig.add_subplot(321)
self.stackedBarPlot(ax1,
d,
d_colors,
edgeCols=['#000000']*7,
xLabels=d_labels,
)
plt.title("Straight up stacked bars")
ax2 = fig.add_subplot(322)
self.stackedBarPlot(ax2,
d,
d_colors,
edgeCols=['#000000']*7,
xLabels=d_labels,
scale=True
)
plt.title("Scaled bars")
ax3 = fig.add_subplot(323)
self.stackedBarPlot(ax3,
d,
d_colors,
edgeCols=['#000000']*7,
xLabels=d_labels,
heights=d_heights,
yTicks=7,
)
plt.title("Bars with set heights")
ax4 = fig.add_subplot(324)
self.stackedBarPlot(ax4,
d,
d_colors,
edgeCols=['#000000']*7,
xLabels=d_labels,
yTicks=7,
widths=d_widths,
scale=True
)
plt.title("Scaled bars with set widths")
ax5 = fig.add_subplot(325)
self.stackedBarPlot(ax5,
d,
d_colors,
edgeCols=['#000000']*7,
xLabels=d_labels,
gap=gap
)
plt.title("Straight up stacked bars + gaps")
ax6 = fig.add_subplot(326)
self.stackedBarPlot(ax6,
d,
d_colors,
edgeCols=['#000000']*7,
xLabels=d_labels,
scale=True,
gap=gap,
endGaps=True
)
plt.title("Scaled bars + gaps + end gaps")
# We change the fontsize of minor ticks label
fig.subplots_adjust(bottom=0.4)
plt.tight_layout()
plt.show()
plt.close(fig)
del fig
def stackedBarPlot(self,
ax, # axes to plot onto
data, # data to plot
cols, # colors for each level
xLabels = None, # bar specific labels
yTicks = 6., # information used for making y ticks ["none", <int> or [[tick_pos1, tick_pos2, ... ],[tick_label_1, tick_label2, ...]]
edgeCols=None, # colors for edges
showFirst=-1, # only plot the first <showFirst> bars
scale=False, # scale bars to same height
widths=None, # set widths for each bar
heights=None, # set heights for each bar
ylabel='', # label for x axis
xlabel='', # label for y axis
gap=0., # gap between bars
endGaps=False # allow gaps at end of bar chart (only used if gaps != 0.)
):
#------------------------------------------------------------------------------
# data fixeratering
# make sure this makes sense
if showFirst != -1:
showFirst = np.min([showFirst, np.shape(data)[0]])
data_copy = np.copy(data[:showFirst]).transpose().astype('float')
data_shape = np.shape(data_copy)
if heights is not None:
heights = heights[:showFirst]
if widths is not None:
widths = widths[:showFirst]
showFirst = -1
else:
data_copy = np.copy(data).transpose()
data_shape = np.shape(data_copy)
# determine the number of bars and corresponding levels from the shape of the data
num_bars = data_shape[1]
levels = data_shape[0]
if widths is None:
widths = np.array([1] * num_bars)
x = np.arange(num_bars)
else:
x = [0]
for i in range(1, len(widths)):
x.append(x[i-1] + (widths[i-1] + widths[i])/2)
# stack the data --
# replace the value in each level by the cumulative sum of all preceding levels
data_stack = np.reshape([float(i) for i in np.ravel(np.cumsum(data_copy, axis=0))], data_shape)
# scale the data is needed
if scale:
data_copy /= data_stack[levels-1]
data_stack /= data_stack[levels-1]
if heights is not None:
print("WARNING: setting scale and heights does not make sense.")
heights = None
elif heights is not None:
data_copy /= data_stack[levels-1]
data_stack /= data_stack[levels-1]
for i in np.arange(num_bars):
data_copy[:,i] *= heights[i]
data_stack[:,i] *= heights[i]
#------------------------------------------------------------------------------
# ticks
if yTicks is not "none":
# it is either a set of ticks or the number of auto ticks to make
real_ticks = True
try:
k = len(yTicks[1])
except:
real_ticks = False
if not real_ticks:
yTicks = float(yTicks)
if scale:
# make the ticks line up to 100 %
y_ticks_at = np.arange(yTicks)/(yTicks-1)
y_tick_labels = np.array(["%0.2f"%(i * 100) for i in y_ticks_at])
else:
# space the ticks along the y axis
y_ticks_at = np.arange(yTicks)/(yTicks-1)*np.max(data_stack)
y_tick_labels = np.array([str(i) for i in y_ticks_at])
yTicks=(y_ticks_at, y_tick_labels)
#------------------------------------------------------------------------------
# plot
if edgeCols is None:
edgeCols = ["none"]*len(cols)
# take cae of gaps
gapd_widths = [i - gap for i in widths]
# bars
ax.bar(x,
data_stack[0],
color=cols[0],
edgecolor=edgeCols[0],
width=gapd_widths,
linewidth=0.5,
align='center'
)
for i in np.arange(1,levels):
ax.bar(x,
data_copy[i],
bottom=data_stack[i-1],
color=cols[i],
edgecolor=edgeCols[i],
width=gapd_widths,
linewidth=0.5,
align='center'
)
# borders
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["left"].set_visible(False)
# make ticks if necessary
if yTicks is not "none":
ax.tick_params(axis='y', which='both', labelsize=8, direction="out")
ax.yaxis.tick_left()
plt.yticks(yTicks[0], yTicks[1])
else:
plt.yticks([], [])
if xLabels is not None:
ax.tick_params(axis='x', which='both', labelsize=8, direction="out")
ax.xaxis.tick_bottom()
plt.xticks(x, xLabels, rotation='vertical')
else:
plt.xticks([], [])
# limits
if endGaps:
ax.set_xlim(-1.*widths[0]/2. - gap/2., np.sum(widths)-widths[0]/2. + gap/2.)
else:
ax.set_xlim(-1.*widths[0]/2. + gap/2., np.sum(widths)-widths[0]/2. - gap/2.)
ax.set_ylim(0, yTicks[0][-1])#np.max(data_stack))
# labels
if xlabel != '':
plt.xlabel(xlabel)
if ylabel != '':
plt.ylabel(ylabel)
###############################################################################
###############################################################################
###############################################################################
###############################################################################
if __name__ == '__main__':
SBG = StackedBarGrapher()
SBG.demo()
###############################################################################
###############################################################################
###############################################################################
###############################################################################