We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
bokeh.charts.Bar displays overlapping bars
This is pretty minor, but the Bar class makes bar charts with overlapping bars if there are more than 4 values.

The widths are currently hardcoded, but it would be nice if they were adjusted based on the data and/or adjustable through a keyword argument, etc.

https://github.com/ContinuumIO/bokeh/blob/8ddcb1bde4c52be89c4ba23ec14dbe7293176f48/bokeh/charts/bar.py#L177

Here's a modified version of the example in the class docstring.  It just duplicates categories so that there are "too many" categories.

```
import numpy as np
from collections import OrderedDict
from bokeh.charts import Bar
from bokeh.sampledata.olympics2014 import data

from bokeh.sampledata.olympics2014 import data
data = {d['abbr']: d['medals'] for d in data['data'] if d['medals']['total'] > 0}
countries = sorted(data.keys(), key=lambda x: data[x]['total'], reverse=True)[:5]
gold = np.array([data[abbr]['gold'] for abbr in countries], dtype=np.float)
silver = np.array([data[abbr]['silver'] for abbr in countries], dtype=np.float)
bronze = np.array([data[abbr]['bronze'] for abbr in countries], dtype=np.float)
medals = OrderedDict(bronze=bronze, silver=silver, gold=gold, gold2=gold, gold3=gold, gold4=gold)

bar = Bar(medals, countries)
bar.title("stacked, dict_input").xlabel("countries").ylabel("medals")\
.legend(True).width(800).height(400).notebook().show()
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `bokeh/charts/bar.py`
Content:
```
1 """This is the Bokeh charts interface. It gives you a high level API to build
2 complex plot is a simple way.
3 
4 This is the Bar class which lets you build your Bar charts just passing
5 the arguments to the Chart class and calling the proper functions.
6 It also add a new chained stacked method.
7 """
8 #-----------------------------------------------------------------------------
9 # Copyright (c) 2012 - 2014, Continuum Analytics, Inc. All rights reserved.
10 #
11 # Powered by the Bokeh Development Team.
12 #
13 # The full license is in the file LICENCE.txt, distributed with this software.
14 #-----------------------------------------------------------------------------
15 
16 #-----------------------------------------------------------------------------
17 # Imports
18 #-----------------------------------------------------------------------------
19 
20 import numpy as np
21 import pandas as pd
22 
23 from ._chartobject import ChartObject
24 
25 from ..objects import ColumnDataSource, FactorRange, Range1d
26 
27 #-----------------------------------------------------------------------------
28 # Classes and functions
29 #-----------------------------------------------------------------------------
30 
31 
32 class Bar(ChartObject):
33     """This is the Bar class and it is in charge of plotting
34     Bar chart (grouped and stacked) in an easy and intuitive way.
35 
36     Essentially, it provides a way to ingest the data, make the proper
37     calculations and push the references into a source object.
38     We additionally make calculations for the ranges.
39     And finally add the needed glyphs (rects) taking the references
40     from the source.
41 
42     Examples:
43 
44         from collections import OrderedDict
45 
46         import numpy as np
47 
48         from bokeh.charts import Bar
49         from bokeh.sampledata.olympics2014 import data
50 
51         data = {d['abbr']: d['medals'] for d in data['data'] if d['medals']['total'] > 0}
52 
53         countries = sorted(data.keys(), key=lambda x: data[x]['total'], reverse=True)
54 
55         gold = np.array([data[abbr]['gold'] for abbr in countries], dtype=np.float)
56         silver = np.array([data[abbr]['silver'] for abbr in countries], dtype=np.float)
57         bronze = np.array([data[abbr]['bronze'] for abbr in countries], dtype=np.float)
58 
59         medals = OrderedDict(bronze=bronze, silver=silver, gold=gold)
60 
61         bar = Bar(medals, countries)
62         bar.title("stacked, dict_input").xlabel("countries").ylabel("medals")\
63 .legend(True).width(600).height(400).stacked().notebook().show()
64     """
65     def __init__(self, value, cat=None, stacked=False,
66                  title=None, xlabel=None, ylabel=None, legend=False,
67                  xscale="categorical", yscale="linear", width=800, height=600,
68                  tools=True, filename=False, server=False, notebook=False):
69         """
70         Args:
71             value (dict): a dict containing the data with names as a key
72                 and the data as a value.
73             cat (list or bool, optional): list of string representing the categories.
74                 Defaults to None.
75             stacked (bool, optional): to see the bars stacked or grouped.
76                 Defaults to False, so grouping is assumed.
77             title (str, optional): the title of your plot. Defaults to None.
78             xlabel (str, optional): the x-axis label of your plot.
79                 Defaults to None.
80             ylabel (str, optional): the y-axis label of your plot.
81                 Defaults to None.
82             legend (str, optional): the legend of your plot. The legend content is
83                 inferred from incoming input.It can be ``top_left``,
84                 ``top_right``, ``bottom_left``, ``bottom_right``.
85                 It is ``top_right`` is you set it as True.
86                 Defaults to None.
87             xscale (str, optional): the x-axis type scale of your plot. It can be
88                 ``linear``, ``datetime`` or ``categorical``.
89                 Defaults to ``linear``.
90             yscale (str, optional): the y-axis type scale of your plot. It can be
91                 ``linear``, ``datetime`` or ``categorical``.
92                 Defaults to ``linear``.
93             width (int, optional): the width of your plot in pixels.
94                 Defaults to 800.
95             height (int, optional): the height of you plot in pixels.
96                 Defaults to 600.
97             tools (bool, optional): to enable or disable the tools in your plot.
98                 Defaults to True
99             filename (str or bool, optional): the name of the file where your plot.
100                 will be written. If you pass True to this argument, it will use
101                 ``untitled`` as a filename.
102                 Defaults to False.
103             server (str or bool, optional): the name of your plot in the server.
104                 If you pass True to this argument, it will use ``untitled``
105                 as the name in the server.
106                 Defaults to False.
107             notebook (bool or optional):if you want to output (or not) your plot into the
108                 IPython notebook.
109                 Defaults to False.
110 
111         Attributes:
112             source (obj): datasource object for your plot,
113                 initialized as a dummy None.
114             xdr (obj): x-associated datarange object for you plot,
115                 initialized as a dummy None.
116             ydr (obj): y-associated datarange object for you plot,
117                 initialized as a dummy None.
118             groups (list): to be filled with the incoming groups of data.
119                 Useful for legend construction.
120             data (dict): to be filled with the incoming data and be passed
121                 to the ColumnDataSource in each chart inherited class.
122                 Needed for _set_And_get method.
123             attr (list): to be filled with the new attributes created after
124                 loading the data dict.
125                 Needed for _set_And_get method.
126         """
127         self.cat = cat
128         self.value = value
129         self.__stacked = stacked
130         self.source = None
131         self.xdr = None
132         self.ydr = None
133         self.groups = []
134         self.data = dict()
135         self.attr = []
136         super(Bar, self).__init__(title, xlabel, ylabel, legend,
137                                   xscale, yscale, width, height,
138                                   tools, filename, server, notebook)
139 
140     def stacked(self, stacked=True):
141         """Set the bars stacked on your chart.
142 
143         Args:
144             stacked (bool, optional): whether to stack the bars
145                 in your plot (default: True).
146 
147         Returns:
148             self: the chart object being configured.
149         """
150         self._stacked = stacked
151         return self
152 
153     def check_attr(self):
154         """Check if any of the chained method were used.
155 
156         If they were not used, it assign the init parameters content by default.
157         """
158         super(Bar, self).check_attr()
159 
160         # add specific chained method
161         if not hasattr(self, '_stacked'):
162             self._stacked = self.__stacked
163 
164     def get_data(self, cat, **value):
165         """Take the Bar data from the input **value.
166 
167         It calculates the chart properties accordingly. Then build a dict
168         containing references to all the calculated points to be used by
169         the rect glyph inside the ``draw`` method.
170 
171         Args:
172             cat (list): categories as a list of strings
173             values (dict or pd obj): the values to be plotted as bars.
174         """
175         self.cat = cat
176         self.width = [0.8] * len(self.cat)
177         self.width_cat = [0.2] * len(self.cat)
178         self.zero = np.zeros(len(self.cat))
179         self.data = dict(cat=self.cat, width=self.width, width_cat=self.width_cat, zero=self.zero)
180 
181         # assuming value is a dict, ordered dict
182         self.value = value
183 
184         # list to save all the attributes we are going to create
185         self.attr = []
186 
187         # list to save all the groups available in the incomming input
188         # Grouping
189         step = np.linspace(0, 1.0, len(self.value.keys()) + 1, endpoint=False)
190 
191         self.groups.extend(self.value.keys())
192 
193         for i, val in enumerate(self.value.keys()):
194             self._set_and_get("", val, self.value[val])
195             self._set_and_get("mid", val, self.value[val] / 2)
196             self._set_and_get("stacked", val, self.zero + self.value[val] / 2)
197             # Grouped
198             self._set_and_get("cat", val, [c + ":" + str(step[i + 1]) for c in self.cat])
199             # Stacked
200             self.zero += self.value[val]
201 
202     def get_source(self, stacked):
203         """Push the Bar data into the ColumnDataSource and calculate the proper ranges.
204 
205         Args:
206             stacked (bool): whether to stack the bars in your plot.
207         """
208         self.source = ColumnDataSource(self.data)
209         self.xdr = FactorRange(factors=self.source.data["cat"])
210         if stacked:
211             self.ydr = Range1d(start=0, end=1.1 * max(self.zero))
212         else:
213             cat = [i for i in self.attr if not i.startswith(("mid", "stacked", "cat"))]
214             end = 1.1 * max(max(self.data[i]) for i in cat)
215             self.ydr = Range1d(start=0, end=end)
216 
217     def draw(self, stacked):
218         """Use the rect glyphs to display the bars.
219 
220         Takes reference points from data loaded at the ColumnDataSurce.
221 
222         Args:
223             stacked (bool): whether to stack the bars in your plot.
224         """
225         self.quartet = list(self._chunker(self.attr, 4))
226         colors = self._set_colors(self.quartet)
227 
228         # quartet elements are: [data, mid, stacked, cat]
229         for i, quartet in enumerate(self.quartet):
230             if stacked:
231                 self.chart.make_rect(self.source, "cat", quartet[2], "width", quartet[0], colors[i], "white", None)
232             else:  # Grouped
233                 self.chart.make_rect(self.source, quartet[3], quartet[1], "width_cat", quartet[0], colors[i], "white", None)
234 
235     def show(self):
236         """Main Bar show method.
237 
238         It essentially checks for chained methods, creates the chart,
239         pass data into the plot object, draws the glyphs according
240         to the data and shows the chart in the selected output.
241 
242         .. note:: the show method can not be chained. It has to be called
243         at the end of the chain.
244         """
245         # if we pass a pandas df, the cat are guessed
246         if isinstance(self.value, pd.DataFrame):
247             self.cat = self.value.index.values.tolist()
248 
249         # we need to check the chained method attr
250         self.check_attr()
251         # we create the chart object
252         self.create_chart()
253         # we start the plot (adds axis, grids and tools)
254         self.start_plot(xgrid=False)
255         # we get the data from the incoming input
256         self.get_data(self.cat, **self.value)
257         # we filled the source and ranges with the calculated data
258         self.get_source(self._stacked)
259         # we dynamically inject the source and ranges into the plot
260         self.add_data_plot(self.xdr, self.ydr)
261         # we add the glyphs into the plot
262         self.draw(self._stacked)
263         # we pass info to build the legend
264         self.end_plot(self.groups)
265         # and finally we show it
266         self.show_chart()
267 
268     # Some helper methods
269     def _set_and_get(self, prefix, val, content):
270         """Set a new attr and then get it to fill the self.data dict.
271 
272         Keep track of the attributes created.
273 
274         Args:
275             prefix (str): prefix of the new attribute
276             val (string): name of the new attribute
277             content (obj): content of the new attribute
278         """
279         setattr(self, prefix + val, content)
280         self.data[prefix + val] = getattr(self, prefix + val)
281         self.attr.append(prefix + val)
282
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/bokeh/charts/bar.py b/bokeh/charts/bar.py
--- a/bokeh/charts/bar.py
+++ b/bokeh/charts/bar.py
@@ -174,7 +174,10 @@
         """
         self.cat = cat
         self.width = [0.8] * len(self.cat)
-        self.width_cat = [0.2] * len(self.cat)
+        # width should decrease proportionally to the value length.
+        # 1./len(value) doesn't work well as the width needs to decrease a
+        # little bit faster
+        self.width_cat = [min(0.2, (1./len(value))**1.1)] * len(self.cat)
         self.zero = np.zeros(len(self.cat))
         self.data = dict(cat=self.cat, width=self.width, width_cat=self.width_cat, zero=self.zero)

{"golden_diff": "diff --git a/bokeh/charts/bar.py b/bokeh/charts/bar.py\n--- a/bokeh/charts/bar.py\n+++ b/bokeh/charts/bar.py\n@@ -174,7 +174,10 @@\n         \"\"\"\n         self.cat = cat\n         self.width = [0.8] * len(self.cat)\n-        self.width_cat = [0.2] * len(self.cat)\n+        # width should decrease proportionally to the value length.\n+        # 1./len(value) doesn't work well as the width needs to decrease a\n+        # little bit faster\n+        self.width_cat = [min(0.2, (1./len(value))**1.1)] * len(self.cat)\n         self.zero = np.zeros(len(self.cat))\n         self.data = dict(cat=self.cat, width=self.width, width_cat=self.width_cat, zero=self.zero)\n", "issue": "bokeh.charts.Bar displays overlapping bars\nThis is pretty minor, but the Bar class makes bar charts with overlapping bars if there are more than 4 values.\n\nThe widths are currently hardcoded, but it would be nice if they were adjusted based on the data and/or adjustable through a keyword argument, etc.\n\nhttps://github.com/ContinuumIO/bokeh/blob/8ddcb1bde4c52be89c4ba23ec14dbe7293176f48/bokeh/charts/bar.py#L177\n\nHere's a modified version of the example in the class docstring.  It just duplicates categories so that there are \"too many\" categories.\n\n```\nimport numpy as np\nfrom collections import OrderedDict\nfrom bokeh.charts import Bar\nfrom bokeh.sampledata.olympics2014 import data\n\nfrom bokeh.sampledata.olympics2014 import data\ndata = {d['abbr']: d['medals'] for d in data['data'] if d['medals']['total'] > 0}\ncountries = sorted(data.keys(), key=lambda x: data[x]['total'], reverse=True)[:5]\ngold = np.array([data[abbr]['gold'] for abbr in countries], dtype=np.float)\nsilver = np.array([data[abbr]['silver'] for abbr in countries], dtype=np.float)\nbronze = np.array([data[abbr]['bronze'] for abbr in countries], dtype=np.float)\nmedals = OrderedDict(bronze=bronze, silver=silver, gold=gold, gold2=gold, gold3=gold, gold4=gold)\n\nbar = Bar(medals, countries)\nbar.title(\"stacked, dict_input\").xlabel(\"countries\").ylabel(\"medals\")\\\n.legend(True).width(800).height(400).notebook().show()\n```\n\n", "before_files": [{"content": "\"\"\"This is the Bokeh charts interface. It gives you a high level API to build\ncomplex plot is a simple way.\n\nThis is the Bar class which lets you build your Bar charts just passing\nthe arguments to the Chart class and calling the proper functions.\nIt also add a new chained stacked method.\n\"\"\"\n#-----------------------------------------------------------------------------\n# Copyright (c) 2012 - 2014, Continuum Analytics, Inc. All rights reserved.\n#\n# Powered by the Bokeh Development Team.\n#\n# The full license is in the file LICENCE.txt, distributed with this software.\n#-----------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------\n# Imports\n#-----------------------------------------------------------------------------\n\nimport numpy as np\nimport pandas as pd\n\nfrom ._chartobject import ChartObject\n\nfrom ..objects import ColumnDataSource, FactorRange, Range1d\n\n#-----------------------------------------------------------------------------\n# Classes and functions\n#-----------------------------------------------------------------------------\n\n\nclass Bar(ChartObject):\n    \"\"\"This is the Bar class and it is in charge of plotting\n    Bar chart (grouped and stacked) in an easy and intuitive way.\n\n    Essentially, it provides a way to ingest the data, make the proper\n    calculations and push the references into a source object.\n    We additionally make calculations for the ranges.\n    And finally add the needed glyphs (rects) taking the references\n    from the source.\n\n    Examples:\n\n        from collections import OrderedDict\n\n        import numpy as np\n\n        from bokeh.charts import Bar\n        from bokeh.sampledata.olympics2014 import data\n\n        data = {d['abbr']: d['medals'] for d in data['data'] if d['medals']['total'] > 0}\n\n        countries = sorted(data.keys(), key=lambda x: data[x]['total'], reverse=True)\n\n        gold = np.array([data[abbr]['gold'] for abbr in countries], dtype=np.float)\n        silver = np.array([data[abbr]['silver'] for abbr in countries], dtype=np.float)\n        bronze = np.array([data[abbr]['bronze'] for abbr in countries], dtype=np.float)\n\n        medals = OrderedDict(bronze=bronze, silver=silver, gold=gold)\n\n        bar = Bar(medals, countries)\n        bar.title(\"stacked, dict_input\").xlabel(\"countries\").ylabel(\"medals\")\\\n.legend(True).width(600).height(400).stacked().notebook().show()\n    \"\"\"\n    def __init__(self, value, cat=None, stacked=False,\n                 title=None, xlabel=None, ylabel=None, legend=False,\n                 xscale=\"categorical\", yscale=\"linear\", width=800, height=600,\n                 tools=True, filename=False, server=False, notebook=False):\n        \"\"\"\n        Args:\n            value (dict): a dict containing the data with names as a key\n                and the data as a value.\n            cat (list or bool, optional): list of string representing the categories.\n                Defaults to None.\n            stacked (bool, optional): to see the bars stacked or grouped.\n                Defaults to False, so grouping is assumed.\n            title (str, optional): the title of your plot. Defaults to None.\n            xlabel (str, optional): the x-axis label of your plot.\n                Defaults to None.\n            ylabel (str, optional): the y-axis label of your plot.\n                Defaults to None.\n            legend (str, optional): the legend of your plot. The legend content is\n                inferred from incoming input.It can be ``top_left``,\n                ``top_right``, ``bottom_left``, ``bottom_right``.\n                It is ``top_right`` is you set it as True.\n                Defaults to None.\n            xscale (str, optional): the x-axis type scale of your plot. It can be\n                ``linear``, ``datetime`` or ``categorical``.\n                Defaults to ``linear``.\n            yscale (str, optional): the y-axis type scale of your plot. It can be\n                ``linear``, ``datetime`` or ``categorical``.\n                Defaults to ``linear``.\n            width (int, optional): the width of your plot in pixels.\n                Defaults to 800.\n            height (int, optional): the height of you plot in pixels.\n                Defaults to 600.\n            tools (bool, optional): to enable or disable the tools in your plot.\n                Defaults to True\n            filename (str or bool, optional): the name of the file where your plot.\n                will be written. If you pass True to this argument, it will use\n                ``untitled`` as a filename.\n                Defaults to False.\n            server (str or bool, optional): the name of your plot in the server.\n                If you pass True to this argument, it will use ``untitled``\n                as the name in the server.\n                Defaults to False.\n            notebook (bool or optional):if you want to output (or not) your plot into the\n                IPython notebook.\n                Defaults to False.\n\n        Attributes:\n            source (obj): datasource object for your plot,\n                initialized as a dummy None.\n            xdr (obj): x-associated datarange object for you plot,\n                initialized as a dummy None.\n            ydr (obj): y-associated datarange object for you plot,\n                initialized as a dummy None.\n            groups (list): to be filled with the incoming groups of data.\n                Useful for legend construction.\n            data (dict): to be filled with the incoming data and be passed\n                to the ColumnDataSource in each chart inherited class.\n                Needed for _set_And_get method.\n            attr (list): to be filled with the new attributes created after\n                loading the data dict.\n                Needed for _set_And_get method.\n        \"\"\"\n        self.cat = cat\n        self.value = value\n        self.__stacked = stacked\n        self.source = None\n        self.xdr = None\n        self.ydr = None\n        self.groups = []\n        self.data = dict()\n        self.attr = []\n        super(Bar, self).__init__(title, xlabel, ylabel, legend,\n                                  xscale, yscale, width, height,\n                                  tools, filename, server, notebook)\n\n    def stacked(self, stacked=True):\n        \"\"\"Set the bars stacked on your chart.\n\n        Args:\n            stacked (bool, optional): whether to stack the bars\n                in your plot (default: True).\n\n        Returns:\n            self: the chart object being configured.\n        \"\"\"\n        self._stacked = stacked\n        return self\n\n    def check_attr(self):\n        \"\"\"Check if any of the chained method were used.\n\n        If they were not used, it assign the init parameters content by default.\n        \"\"\"\n        super(Bar, self).check_attr()\n\n        # add specific chained method\n        if not hasattr(self, '_stacked'):\n            self._stacked = self.__stacked\n\n    def get_data(self, cat, **value):\n        \"\"\"Take the Bar data from the input **value.\n\n        It calculates the chart properties accordingly. Then build a dict\n        containing references to all the calculated points to be used by\n        the rect glyph inside the ``draw`` method.\n\n        Args:\n            cat (list): categories as a list of strings\n            values (dict or pd obj): the values to be plotted as bars.\n        \"\"\"\n        self.cat = cat\n        self.width = [0.8] * len(self.cat)\n        self.width_cat = [0.2] * len(self.cat)\n        self.zero = np.zeros(len(self.cat))\n        self.data = dict(cat=self.cat, width=self.width, width_cat=self.width_cat, zero=self.zero)\n\n        # assuming value is a dict, ordered dict\n        self.value = value\n\n        # list to save all the attributes we are going to create\n        self.attr = []\n\n        # list to save all the groups available in the incomming input\n        # Grouping\n        step = np.linspace(0, 1.0, len(self.value.keys()) + 1, endpoint=False)\n\n        self.groups.extend(self.value.keys())\n\n        for i, val in enumerate(self.value.keys()):\n            self._set_and_get(\"\", val, self.value[val])\n            self._set_and_get(\"mid\", val, self.value[val] / 2)\n            self._set_and_get(\"stacked\", val, self.zero + self.value[val] / 2)\n            # Grouped\n            self._set_and_get(\"cat\", val, [c + \":\" + str(step[i + 1]) for c in self.cat])\n            # Stacked\n            self.zero += self.value[val]\n\n    def get_source(self, stacked):\n        \"\"\"Push the Bar data into the ColumnDataSource and calculate the proper ranges.\n\n        Args:\n            stacked (bool): whether to stack the bars in your plot.\n        \"\"\"\n        self.source = ColumnDataSource(self.data)\n        self.xdr = FactorRange(factors=self.source.data[\"cat\"])\n        if stacked:\n            self.ydr = Range1d(start=0, end=1.1 * max(self.zero))\n        else:\n            cat = [i for i in self.attr if not i.startswith((\"mid\", \"stacked\", \"cat\"))]\n            end = 1.1 * max(max(self.data[i]) for i in cat)\n            self.ydr = Range1d(start=0, end=end)\n\n    def draw(self, stacked):\n        \"\"\"Use the rect glyphs to display the bars.\n\n        Takes reference points from data loaded at the ColumnDataSurce.\n\n        Args:\n            stacked (bool): whether to stack the bars in your plot.\n        \"\"\"\n        self.quartet = list(self._chunker(self.attr, 4))\n        colors = self._set_colors(self.quartet)\n\n        # quartet elements are: [data, mid, stacked, cat]\n        for i, quartet in enumerate(self.quartet):\n            if stacked:\n                self.chart.make_rect(self.source, \"cat\", quartet[2], \"width\", quartet[0], colors[i], \"white\", None)\n            else:  # Grouped\n                self.chart.make_rect(self.source, quartet[3], quartet[1], \"width_cat\", quartet[0], colors[i], \"white\", None)\n\n    def show(self):\n        \"\"\"Main Bar show method.\n\n        It essentially checks for chained methods, creates the chart,\n        pass data into the plot object, draws the glyphs according\n        to the data and shows the chart in the selected output.\n\n        .. note:: the show method can not be chained. It has to be called\n        at the end of the chain.\n        \"\"\"\n        # if we pass a pandas df, the cat are guessed\n        if isinstance(self.value, pd.DataFrame):\n            self.cat = self.value.index.values.tolist()\n\n        # we need to check the chained method attr\n        self.check_attr()\n        # we create the chart object\n        self.create_chart()\n        # we start the plot (adds axis, grids and tools)\n        self.start_plot(xgrid=False)\n        # we get the data from the incoming input\n        self.get_data(self.cat, **self.value)\n        # we filled the source and ranges with the calculated data\n        self.get_source(self._stacked)\n        # we dynamically inject the source and ranges into the plot\n        self.add_data_plot(self.xdr, self.ydr)\n        # we add the glyphs into the plot\n        self.draw(self._stacked)\n        # we pass info to build the legend\n        self.end_plot(self.groups)\n        # and finally we show it\n        self.show_chart()\n\n    # Some helper methods\n    def _set_and_get(self, prefix, val, content):\n        \"\"\"Set a new attr and then get it to fill the self.data dict.\n\n        Keep track of the attributes created.\n\n        Args:\n            prefix (str): prefix of the new attribute\n            val (string): name of the new attribute\n            content (obj): content of the new attribute\n        \"\"\"\n        setattr(self, prefix + val, content)\n        self.data[prefix + val] = getattr(self, prefix + val)\n        self.attr.append(prefix + val)\n", "path": "bokeh/charts/bar.py"}], "after_files": [{"content": "\"\"\"This is the Bokeh charts interface. It gives you a high level API to build\ncomplex plot is a simple way.\n\nThis is the Bar class which lets you build your Bar charts just passing\nthe arguments to the Chart class and calling the proper functions.\nIt also add a new chained stacked method.\n\"\"\"\n#-----------------------------------------------------------------------------\n# Copyright (c) 2012 - 2014, Continuum Analytics, Inc. All rights reserved.\n#\n# Powered by the Bokeh Development Team.\n#\n# The full license is in the file LICENCE.txt, distributed with this software.\n#-----------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------\n# Imports\n#-----------------------------------------------------------------------------\n\nimport numpy as np\nimport pandas as pd\n\nfrom ._chartobject import ChartObject\n\nfrom ..objects import ColumnDataSource, FactorRange, Range1d\n\n#-----------------------------------------------------------------------------\n# Classes and functions\n#-----------------------------------------------------------------------------\n\n\nclass Bar(ChartObject):\n    \"\"\"This is the Bar class and it is in charge of plotting\n    Bar chart (grouped and stacked) in an easy and intuitive way.\n\n    Essentially, it provides a way to ingest the data, make the proper\n    calculations and push the references into a source object.\n    We additionally make calculations for the ranges.\n    And finally add the needed glyphs (rects) taking the references\n    from the source.\n\n    Examples:\n\n        from collections import OrderedDict\n\n        import numpy as np\n\n        from bokeh.charts import Bar\n        from bokeh.sampledata.olympics2014 import data\n\n        data = {d['abbr']: d['medals'] for d in data['data'] if d['medals']['total'] > 0}\n\n        countries = sorted(data.keys(), key=lambda x: data[x]['total'], reverse=True)\n\n        gold = np.array([data[abbr]['gold'] for abbr in countries], dtype=np.float)\n        silver = np.array([data[abbr]['silver'] for abbr in countries], dtype=np.float)\n        bronze = np.array([data[abbr]['bronze'] for abbr in countries], dtype=np.float)\n\n        medals = OrderedDict(bronze=bronze, silver=silver, gold=gold)\n\n        bar = Bar(medals, countries)\n        bar.title(\"stacked, dict_input\").xlabel(\"countries\").ylabel(\"medals\")\\\n.legend(True).width(600).height(400).stacked().notebook().show()\n    \"\"\"\n    def __init__(self, value, cat=None, stacked=False,\n                 title=None, xlabel=None, ylabel=None, legend=False,\n                 xscale=\"categorical\", yscale=\"linear\", width=800, height=600,\n                 tools=True, filename=False, server=False, notebook=False):\n        \"\"\"\n        Args:\n            value (dict): a dict containing the data with names as a key\n                and the data as a value.\n            cat (list or bool, optional): list of string representing the categories.\n                Defaults to None.\n            stacked (bool, optional): to see the bars stacked or grouped.\n                Defaults to False, so grouping is assumed.\n            title (str, optional): the title of your plot. Defaults to None.\n            xlabel (str, optional): the x-axis label of your plot.\n                Defaults to None.\n            ylabel (str, optional): the y-axis label of your plot.\n                Defaults to None.\n            legend (str, optional): the legend of your plot. The legend content is\n                inferred from incoming input.It can be ``top_left``,\n                ``top_right``, ``bottom_left``, ``bottom_right``.\n                It is ``top_right`` is you set it as True.\n                Defaults to None.\n            xscale (str, optional): the x-axis type scale of your plot. It can be\n                ``linear``, ``datetime`` or ``categorical``.\n                Defaults to ``linear``.\n            yscale (str, optional): the y-axis type scale of your plot. It can be\n                ``linear``, ``datetime`` or ``categorical``.\n                Defaults to ``linear``.\n            width (int, optional): the width of your plot in pixels.\n                Defaults to 800.\n            height (int, optional): the height of you plot in pixels.\n                Defaults to 600.\n            tools (bool, optional): to enable or disable the tools in your plot.\n                Defaults to True\n            filename (str or bool, optional): the name of the file where your plot.\n                will be written. If you pass True to this argument, it will use\n                ``untitled`` as a filename.\n                Defaults to False.\n            server (str or bool, optional): the name of your plot in the server.\n                If you pass True to this argument, it will use ``untitled``\n                as the name in the server.\n                Defaults to False.\n            notebook (bool or optional):if you want to output (or not) your plot into the\n                IPython notebook.\n                Defaults to False.\n\n        Attributes:\n            source (obj): datasource object for your plot,\n                initialized as a dummy None.\n            xdr (obj): x-associated datarange object for you plot,\n                initialized as a dummy None.\n            ydr (obj): y-associated datarange object for you plot,\n                initialized as a dummy None.\n            groups (list): to be filled with the incoming groups of data.\n                Useful for legend construction.\n            data (dict): to be filled with the incoming data and be passed\n                to the ColumnDataSource in each chart inherited class.\n                Needed for _set_And_get method.\n            attr (list): to be filled with the new attributes created after\n                loading the data dict.\n                Needed for _set_And_get method.\n        \"\"\"\n        self.cat = cat\n        self.value = value\n        self.__stacked = stacked\n        self.source = None\n        self.xdr = None\n        self.ydr = None\n        self.groups = []\n        self.data = dict()\n        self.attr = []\n        super(Bar, self).__init__(title, xlabel, ylabel, legend,\n                                  xscale, yscale, width, height,\n                                  tools, filename, server, notebook)\n\n    def stacked(self, stacked=True):\n        \"\"\"Set the bars stacked on your chart.\n\n        Args:\n            stacked (bool, optional): whether to stack the bars\n                in your plot (default: True).\n\n        Returns:\n            self: the chart object being configured.\n        \"\"\"\n        self._stacked = stacked\n        return self\n\n    def check_attr(self):\n        \"\"\"Check if any of the chained method were used.\n\n        If they were not used, it assign the init parameters content by default.\n        \"\"\"\n        super(Bar, self).check_attr()\n\n        # add specific chained method\n        if not hasattr(self, '_stacked'):\n            self._stacked = self.__stacked\n\n    def get_data(self, cat, **value):\n        \"\"\"Take the Bar data from the input **value.\n\n        It calculates the chart properties accordingly. Then build a dict\n        containing references to all the calculated points to be used by\n        the rect glyph inside the ``draw`` method.\n\n        Args:\n            cat (list): categories as a list of strings\n            values (dict or pd obj): the values to be plotted as bars.\n        \"\"\"\n        self.cat = cat\n        self.width = [0.8] * len(self.cat)\n        # width should decrease proportionally to the value length.\n        # 1./len(value) doesn't work well as the width needs to decrease a\n        # little bit faster\n        self.width_cat = [min(0.2, (1./len(value))**1.1)] * len(self.cat)\n        self.zero = np.zeros(len(self.cat))\n        self.data = dict(cat=self.cat, width=self.width, width_cat=self.width_cat, zero=self.zero)\n\n        # assuming value is a dict, ordered dict\n        self.value = value\n\n        # list to save all the attributes we are going to create\n        self.attr = []\n\n        # list to save all the groups available in the incomming input\n        # Grouping\n        step = np.linspace(0, 1.0, len(self.value.keys()) + 1, endpoint=False)\n\n        self.groups.extend(self.value.keys())\n\n        for i, val in enumerate(self.value.keys()):\n            self._set_and_get(\"\", val, self.value[val])\n            self._set_and_get(\"mid\", val, self.value[val] / 2)\n            self._set_and_get(\"stacked\", val, self.zero + self.value[val] / 2)\n            # Grouped\n            self._set_and_get(\"cat\", val, [c + \":\" + str(step[i + 1]) for c in self.cat])\n            # Stacked\n            self.zero += self.value[val]\n\n    def get_source(self, stacked):\n        \"\"\"Push the Bar data into the ColumnDataSource and calculate the proper ranges.\n\n        Args:\n            stacked (bool): whether to stack the bars in your plot.\n        \"\"\"\n        self.source = ColumnDataSource(self.data)\n        self.xdr = FactorRange(factors=self.source.data[\"cat\"])\n        if stacked:\n            self.ydr = Range1d(start=0, end=1.1 * max(self.zero))\n        else:\n            cat = [i for i in self.attr if not i.startswith((\"mid\", \"stacked\", \"cat\"))]\n            end = 1.1 * max(max(self.data[i]) for i in cat)\n            self.ydr = Range1d(start=0, end=end)\n\n    def draw(self, stacked):\n        \"\"\"Use the rect glyphs to display the bars.\n\n        Takes reference points from data loaded at the ColumnDataSurce.\n\n        Args:\n            stacked (bool): whether to stack the bars in your plot.\n        \"\"\"\n        self.quartet = list(self._chunker(self.attr, 4))\n        colors = self._set_colors(self.quartet)\n\n        # quartet elements are: [data, mid, stacked, cat]\n        for i, quartet in enumerate(self.quartet):\n            if stacked:\n                self.chart.make_rect(self.source, \"cat\", quartet[2], \"width\", quartet[0], colors[i], \"white\", None)\n            else:  # Grouped\n                self.chart.make_rect(self.source, quartet[3], quartet[1], \"width_cat\", quartet[0], colors[i], \"white\", None)\n\n    def show(self):\n        \"\"\"Main Bar show method.\n\n        It essentially checks for chained methods, creates the chart,\n        pass data into the plot object, draws the glyphs according\n        to the data and shows the chart in the selected output.\n\n        .. note:: the show method can not be chained. It has to be called\n        at the end of the chain.\n        \"\"\"\n        # if we pass a pandas df, the cat are guessed\n        if isinstance(self.value, pd.DataFrame):\n            self.cat = self.value.index.values.tolist()\n\n        # we need to check the chained method attr\n        self.check_attr()\n        # we create the chart object\n        self.create_chart()\n        # we start the plot (adds axis, grids and tools)\n        self.start_plot(xgrid=False)\n        # we get the data from the incoming input\n        self.get_data(self.cat, **self.value)\n        # we filled the source and ranges with the calculated data\n        self.get_source(self._stacked)\n        # we dynamically inject the source and ranges into the plot\n        self.add_data_plot(self.xdr, self.ydr)\n        # we add the glyphs into the plot\n        self.draw(self._stacked)\n        # we pass info to build the legend\n        self.end_plot(self.groups)\n        # and finally we show it\n        self.show_chart()\n\n    # Some helper methods\n    def _set_and_get(self, prefix, val, content):\n        \"\"\"Set a new attr and then get it to fill the self.data dict.\n\n        Keep track of the attributes created.\n\n        Args:\n            prefix (str): prefix of the new attribute\n            val (string): name of the new attribute\n            content (obj): content of the new attribute\n        \"\"\"\n        setattr(self, prefix + val, content)\n        self.data[prefix + val] = getattr(self, prefix + val)\n        self.attr.append(prefix + val)\n", "path": "bokeh/charts/bar.py"}]}