Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/plot/bar_chart.py
4034 views
1
"""
2
Bar Charts
3
"""
4
5
#*****************************************************************************
6
# Copyright (C) 2006 Alex Clemesha <[email protected]>,
7
# William Stein <[email protected]>,
8
# 2008 Mike Hansen <[email protected]>,
9
#
10
# Distributed under the terms of the GNU General Public License (GPL)
11
#
12
# This code is distributed in the hope that it will be useful,
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
# General Public License for more details.
16
#
17
# The full text of the GPL is available at:
18
#
19
# http://www.gnu.org/licenses/
20
#*****************************************************************************
21
from sage.plot.primitive import GraphicPrimitive
22
from sage.plot.plot import minmax_data
23
from sage.plot.graphics import Graphics
24
from sage.misc.decorators import options, rename_keyword
25
26
#TODO: make bar_chart more general
27
class BarChart(GraphicPrimitive):
28
"""
29
Graphics primitive that represents a bar chart.
30
31
EXAMPLES::
32
33
sage: from sage.plot.bar_chart import BarChart
34
sage: g = BarChart(range(4), [1,3,2,0], {}); g
35
BarChart defined by a 4 datalist
36
sage: type(g)
37
<class 'sage.plot.bar_chart.BarChart'>
38
"""
39
def __init__(self, ind, datalist, options):
40
"""
41
Initialize a ``BarChart`` primitive.
42
43
EXAMPLES::
44
45
sage: from sage.plot.bar_chart import BarChart
46
sage: BarChart(range(3), [10,3,5], {'width':0.7})
47
BarChart defined by a 3 datalist
48
"""
49
self.datalist = datalist
50
self.ind = ind
51
GraphicPrimitive.__init__(self, options)
52
53
def get_minmax_data(self):
54
"""
55
Returns a dictionary with the bounding box data.
56
57
EXAMPLES::
58
59
sage: b = bar_chart([-2.3,5,-6,12])
60
sage: d = b.get_minmax_data()
61
sage: d['xmin']
62
0
63
sage: d['xmax']
64
4
65
"""
66
return minmax_data([0, len(self.datalist)], self.datalist, dict=True)
67
68
def _allowed_options(self):
69
"""
70
Return the allowed options with descriptions for this graphics
71
primitive. This is used in displaying an error message when the
72
user gives an option that doesn't make sense.
73
74
EXAMPLES::
75
76
sage: from sage.plot.bar_chart import BarChart
77
sage: g = BarChart(range(4), [1,3,2,0], {})
78
sage: list(sorted(g._allowed_options().iteritems()))
79
[('hue', 'The color given as a hue.'), ('legend_label', 'The label for this item in the legend.'), ('rgbcolor', 'The color as an RGB tuple.'), ('width', 'The width of the bars'), ('zorder', 'The layer level in which to draw')]
80
"""
81
return {'rgbcolor':'The color as an RGB tuple.',
82
'hue':'The color given as a hue.',
83
'legend_label':'The label for this item in the legend.',
84
'width':'The width of the bars',
85
'zorder':'The layer level in which to draw'}
86
87
def _repr_(self):
88
"""
89
Return text representation of this bar chart graphics primitive.
90
91
EXAMPLES::
92
93
sage: from sage.plot.bar_chart import BarChart
94
sage: g = BarChart(range(4), [1,3,2,0], {})
95
sage: g._repr_()
96
'BarChart defined by a 4 datalist'
97
"""
98
return "BarChart defined by a %s datalist"%(len(self.datalist))
99
100
def _render_on_subplot(self, subplot):
101
"""
102
Render this bar chart graphics primitive on a matplotlib subplot
103
object.
104
105
EXAMPLES:
106
107
This rendering happens implicitly when the following command
108
is executed::
109
110
sage: bar_chart([1,2,10])
111
"""
112
options = self.options()
113
color = options['rgbcolor']
114
width = float(options['width'])
115
# it is critical to make NumPy arrays of type float below,
116
# or bar will go boom:
117
import numpy
118
ind = numpy.array(self.ind, dtype=float)
119
datalist = numpy.array(self.datalist, dtype=float)
120
subplot.bar(ind, datalist, color=color, width=width, label=options['legend_label'])
121
122
@rename_keyword(color='rgbcolor')
123
@options(width=0.5, rgbcolor=(0,0,1), legend_label=None, aspect_ratio='automatic')
124
def bar_chart(datalist, **options):
125
"""
126
A bar chart of (currently) one list of numerical data.
127
Support for more data lists in progress.
128
129
EXAMPLES:
130
131
A bar_chart with blue bars::
132
133
sage: bar_chart([1,2,3,4])
134
135
A bar_chart with thinner bars::
136
137
sage: bar_chart([x^2 for x in range(1,20)], width=0.2)
138
139
A bar_chart with negative values and red bars::
140
141
sage: bar_chart([-3,5,-6,11], rgbcolor=(1,0,0))
142
143
A bar chart with a legend (it's possible, not necessarily useful)::
144
145
sage: bar_chart([-1,1,-1,1], legend_label='wave')
146
147
Extra options will get passed on to show(), as long as they are valid::
148
149
sage: bar_chart([-2,8,-7,3], rgbcolor=(1,0,0), axes=False)
150
sage: bar_chart([-2,8,-7,3], rgbcolor=(1,0,0)).show(axes=False) # These are equivalent
151
"""
152
dl = len(datalist)
153
#if dl > 1:
154
# print "WARNING, currently only 1 data set allowed"
155
# datalist = datalist[0]
156
if dl == 3:
157
datalist = datalist+[0]
158
#bardata = []
159
#cnt = 1
160
#for pnts in datalist:
161
#ind = [i+cnt/dl for i in range(len(pnts))]
162
#bardata.append([ind, pnts, xrange, yrange])
163
#cnt += 1
164
165
g = Graphics()
166
g._set_extra_kwds(Graphics._extract_kwds_for_show(options))
167
#TODO: improve below for multiple data sets!
168
#cnt = 1
169
#for ind, pnts, xrange, yrange in bardata:
170
#options={'rgbcolor':hue(cnt/dl),'width':0.5/dl}
171
# g._bar_chart(ind, pnts, xrange, yrange, options=options)
172
# cnt += 1
173
#else:
174
ind = range(len(datalist))
175
g.add_primitive(BarChart(ind, datalist, options=options))
176
if options['legend_label']:
177
g.legend(True)
178
return g
179
180