Skip to content

Commit 19969f4

Browse files
authored
Merge pull request #13 from plotly/horizontal-bar
horizontal-bar-charts notebook
2 parents 3ea8dc5 + 114b6e8 commit 19969f4

File tree

1 file changed

+101
-127
lines changed

1 file changed

+101
-127
lines changed

notebooks/horizontal-bar-charts.md

+101-127
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,19 @@ jupyter:
88
format_version: '1.1'
99
jupytext_version: 1.1.1
1010
kernelspec:
11-
display_name: Python 2
11+
display_name: Python 3
1212
language: python
13-
name: python2
13+
name: python3
14+
language_info:
15+
codemirror_mode:
16+
name: ipython
17+
version: 3
18+
file_extension: .py
19+
mimetype: text/x-python
20+
name: python
21+
nbconvert_exporter: python
22+
pygments_lexer: ipython3
23+
version: 3.6.7
1424
plotly:
1525
description: How to make horizontal bar charts in Python with Plotly.
1626
display_as: basic
@@ -24,80 +34,94 @@ jupyter:
2434
permalink: python/horizontal-bar-charts/
2535
thumbnail: thumbnail/horizontal-bar.jpg
2636
title: Horizontal Bar Charts | plotly
37+
v4upgrade: true
2738
---
2839

29-
#### New to Plotly?
30-
Plotly's Python library is free and open source! [Get started](https://plot.ly/python/getting-started/) by downloading the client and [reading the primer](https://plot.ly/python/getting-started/).
31-
<br>You can set up Plotly to work in [online](https://plot.ly/python/getting-started/#initialization-for-online-plotting) or [offline](https://plot.ly/python/getting-started/#initialization-for-offline-plotting) mode, or in [jupyter notebooks](https://plot.ly/python/getting-started/#start-plotting-online).
32-
<br>We also have a quick-reference [cheatsheet](https://images.plot.ly/plotly-documentation/images/python_cheat_sheet.pdf) (new!) to help you get started!
33-
#### Version Check
34-
Plotly's python package is updated frequently. Run `pip install plotly --upgrade` to use the latest version.
40+
See more examples of bar charts (including vertical bar charts) and styling options [here](https://plot.ly/python/bar-charts/).
41+
42+
43+
### Horizontal Bar Chart with plotly express
44+
45+
Plotly express functions take as argument a tidy [pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/getting_started/10min.html). For a horizontal bar char, use the `px.bar` function with `orientation='h'`.
46+
47+
48+
#### Basic Horizontal Bar Chart with plotly express
49+
50+
51+
```python
52+
import plotly.express as px
53+
tips = px.data.tips()
54+
fig = px.bar(tips, x="total_bill", y="day", orientation='h')
55+
fig.show()
56+
```
57+
58+
#### Configure horizontal bar chart
59+
60+
In this example a column is used to color the bars, and we add the information from other columns to the hover data.
3561

3662
```python
37-
import plotly
38-
plotly.__version__
63+
import plotly.express as px
64+
tips = px.data.tips()
65+
fig = px.bar(tips, x="total_bill", y="sex", color='day', orientation='h',
66+
hover_data=["tip", "size"],
67+
height=400,
68+
title='Restaurant bills')
69+
fig.show()
3970
```
4071

72+
### Horizontal Bar Chart with go.Bar
73+
74+
When data are not available as a tidy dataframe, you can use the more generic function `go.Bar` from `plotly.graph_objects`. All the options of `go.Bar` are documented in the reference https://plot.ly/python/reference/#bar
75+
76+
4177
#### Basic Horizontal Bar Chart
4278

4379
```python
44-
import plotly.plotly as py
45-
import plotly.graph_objs as go
80+
import plotly.graph_objects as go
4681

47-
data = [go.Bar(
82+
fig = go.Figure(go.Bar(
4883
x=[20, 14, 23],
4984
y=['giraffes', 'orangutans', 'monkeys'],
50-
orientation = 'h'
51-
)]
85+
orientation='h'))
5286

53-
py.iplot(data, filename='horizontal-bar')
87+
fig.show()
5488
```
5589

5690
### Colored Horizontal Bar Chart
5791

5892
```python
59-
import plotly.plotly as py
60-
import plotly.graph_objs as go
93+
import plotly.graph_objects as go
6194

62-
trace1 = go.Bar(
95+
fig = go.Figure()
96+
fig.add_trace(go.Bar(
6397
y=['giraffes', 'orangutans', 'monkeys'],
6498
x=[20, 14, 23],
6599
name='SF Zoo',
66-
orientation = 'h',
67-
marker = dict(
68-
color = 'rgba(246, 78, 139, 0.6)',
69-
line = dict(
70-
color = 'rgba(246, 78, 139, 1.0)',
71-
width = 3)
100+
orientation='h',
101+
marker=dict(
102+
color='rgba(246, 78, 139, 0.6)',
103+
line=dict(color='rgba(246, 78, 139, 1.0)', width=3)
72104
)
73-
)
74-
trace2 = go.Bar(
105+
))
106+
fig.add_trace(go.Bar(
75107
y=['giraffes', 'orangutans', 'monkeys'],
76108
x=[12, 18, 29],
77109
name='LA Zoo',
78-
orientation = 'h',
79-
marker = dict(
80-
color = 'rgba(58, 71, 80, 0.6)',
81-
line = dict(
82-
color = 'rgba(58, 71, 80, 1.0)',
83-
width = 3)
110+
orientation='h',
111+
marker=dict(
112+
color='rgba(58, 71, 80, 0.6)',
113+
line=dict(color='rgba(58, 71, 80, 1.0)', width=3)
84114
)
85-
)
86-
87-
data = [trace1, trace2]
88-
layout = go.Layout(
89-
barmode='stack'
90-
)
115+
))
91116

92-
fig = go.Figure(data=data, layout=layout)
93-
py.iplot(fig, filename='marker-h-bar')
117+
fig.update_layout(barmode='stack')
118+
fig.show()
94119
```
95120

96121
### Color Palette for Bar Chart
97122

98123
```python
99-
import plotly.plotly as py
100-
import plotly.graph_objs as go
124+
import plotly.graph_objects as go
101125

102126
top_labels = ['Strongly<br>agree', 'Agree', 'Neutral', 'Disagree',
103127
'Strongly<br>disagree']
@@ -117,24 +141,20 @@ y_data = ['The course was effectively<br>organized',
117141
'my<br>ability to think critically about<br>the subject',
118142
'I would recommend this<br>course to a friend']
119143

120-
121-
traces = []
144+
fig = go.Figure()
122145

123146
for i in range(0, len(x_data[0])):
124147
for xd, yd in zip(x_data, y_data):
125-
traces.append(go.Bar(
126-
x=[xd[i]],
127-
y=[yd],
148+
fig.add_trace(go.Bar(
149+
x=[xd[i]], y=[yd],
128150
orientation='h',
129151
marker=dict(
130152
color=colors[i],
131-
line=dict(
132-
color='rgb(248, 248, 249)',
133-
width=1)
153+
line=dict(color='rgb(248, 248, 249)', width=1)
134154
)
135155
))
136156

137-
layout = go.Layout(
157+
fig.update_layout(
138158
xaxis=dict(
139159
showgrid=False,
140160
showline=False,
@@ -151,12 +171,7 @@ layout = go.Layout(
151171
barmode='stack',
152172
paper_bgcolor='rgb(248, 248, 255)',
153173
plot_bgcolor='rgb(248, 248, 255)',
154-
margin=dict(
155-
l=120,
156-
r=10,
157-
t=140,
158-
b=80
159-
),
174+
margin=dict(l=120, r=10, t=140, b=80),
160175
showlegend=False,
161176
)
162177

@@ -205,18 +220,16 @@ for yd, xd in zip(y_data, x_data):
205220
showarrow=False))
206221
space += xd[i]
207222

208-
layout['annotations'] = annotations
223+
fig.update_layout(annotations=annotations)
209224

210-
fig = go.Figure(data=traces, layout=layout)
211-
py.iplot(fig, filename='bar-colorscale')
225+
fig.show()
212226
```
213227

214228
### Bar Chart with Line Plot
215229

216230
```python
217-
import plotly.plotly as py
218-
import plotly.graph_objs as go
219-
from plotly import tools
231+
import plotly.graph_objects as go
232+
from plotly.subplots import make_subplots
220233

221234
import numpy as np
222235

@@ -226,14 +239,17 @@ y_saving = [1.3586, 2.2623000000000002, 4.9821999999999997, 6.5096999999999996,
226239
y_net_worth = [93453.919999999998, 81666.570000000007, 69889.619999999995,
227240
78381.529999999999, 141395.29999999999, 92969.020000000004,
228241
66090.179999999993, 122379.3]
229-
x_saving = ['Japan', 'United Kingdom', 'Canada', 'Netherlands',
230-
'United States', 'Belgium', 'Sweden', 'Switzerland']
231-
x_net_worth = ['Japan', 'United Kingdom', 'Canada', 'Netherlands',
232-
'United States', 'Belgium', 'Sweden', 'Switzerland'
233-
]
234-
trace0 = go.Bar(
242+
x = ['Japan', 'United Kingdom', 'Canada', 'Netherlands',
243+
'United States', 'Belgium', 'Sweden', 'Switzerland']
244+
245+
246+
# Creating two subplots
247+
fig = make_subplots(rows=1, cols=2, specs=[[{}, {}]], shared_xaxes=True,
248+
shared_yaxes=False, vertical_spacing=0.001)
249+
250+
fig.append_trace(go.Bar(
235251
x=y_saving,
236-
y=x_saving,
252+
y=x,
237253
marker=dict(
238254
color='rgba(50, 171, 96, 0.6)',
239255
line=dict(
@@ -242,16 +258,16 @@ trace0 = go.Bar(
242258
),
243259
name='Household savings, percentage of household disposable income',
244260
orientation='h',
245-
)
246-
trace1 = go.Scatter(
247-
x=y_net_worth,
248-
y=x_net_worth,
261+
), 1, 1)
262+
263+
fig.append_trace(go.Scatter(
264+
x=y_net_worth, y=x,
249265
mode='lines+markers',
250-
line=dict(
251-
color='rgb(128, 0, 128)'),
266+
line_color='rgb(128, 0, 128)',
252267
name='Household net worth, Million USD/capita',
253-
)
254-
layout = dict(
268+
), 1, 2)
269+
270+
fig.update_layout(
255271
title='Household savings & net worth for eight OECD countries',
256272
yaxis=dict(
257273
showgrid=False,
@@ -283,19 +299,8 @@ layout = dict(
283299
side='top',
284300
dtick=25000,
285301
),
286-
legend=dict(
287-
x=0.029,
288-
y=1.038,
289-
font=dict(
290-
size=10,
291-
),
292-
),
293-
margin=dict(
294-
l=100,
295-
r=20,
296-
t=70,
297-
b=70,
298-
),
302+
legend=dict(x=0.029, y=1.038, font_size=10),
303+
margin=dict(l=100, r=20, t=70, b=70),
299304
paper_bgcolor='rgb(248, 248, 255)',
300305
plot_bgcolor='rgb(248, 248, 255)',
301306
)
@@ -306,7 +311,7 @@ y_s = np.round(y_saving, decimals=2)
306311
y_nw = np.rint(y_net_worth)
307312

308313
# Adding labels
309-
for ydn, yd, xd in zip(y_nw, y_s, x_saving):
314+
for ydn, yd, xd in zip(y_nw, y_s, x):
310315
# labeling the scatter savings
311316
annotations.append(dict(xref='x2', yref='y2',
312317
y=xd, x=ydn - 20000,
@@ -328,44 +333,13 @@ annotations.append(dict(xref='paper', yref='paper',
328333
'(2015), Household savings (indicator), ' +
329334
'Household net worth (indicator). doi: ' +
330335
'10.1787/cfc6f499-en (Accessed on 05 June 2015)',
331-
font=dict(family='Arial', size=10,
332-
color='rgb(150,150,150)'),
336+
font=dict(family='Arial', size=10, color='rgb(150,150,150)'),
333337
showarrow=False))
334338

335-
layout['annotations'] = annotations
336-
337-
# Creating two subplots
338-
fig = tools.make_subplots(rows=1, cols=2, specs=[[{}, {}]], shared_xaxes=True,
339-
shared_yaxes=False, vertical_spacing=0.001)
340-
341-
fig.append_trace(trace0, 1, 1)
342-
fig.append_trace(trace1, 1, 2)
339+
fig.update_layout(annotations=annotations)
343340

344-
fig['layout'].update(layout)
345-
py.iplot(fig, filename='oecd-networth-saving-bar-line')
341+
fig.show()
346342
```
347343

348344
### Reference
349345
See more examples of bar charts and styling options [here](https://plot.ly/python/bar-charts/).<br> See https://plot.ly/python/reference/#bar for more information and chart attribute options!
350-
351-
```python
352-
from IPython.display import display, HTML
353-
354-
display(HTML('<link href="//fonts.googleapis.com/css?family=Open+Sans:600,400,300,200|Inconsolata|Ubuntu+Mono:400,700" rel="stylesheet" type="text/css" />'))
355-
display(HTML('<link rel="stylesheet" type="text/css" href="http://help.plot.ly/documentation/all_static/css/ipython-notebook-custom.css">'))
356-
357-
#! pip install git+https://github.com/plotly/publisher.git --upgrade
358-
import publisher
359-
publisher.publish(
360-
'horizontal-bars.ipynb', 'python/horizontal-bar-charts/', 'Horizontal Bar Charts | plotly',
361-
'How to make horizontal bar charts in Python with Plotly.',
362-
title = 'Horizontal Bar Charts | plotly',
363-
name = 'Horizontal Bar Charts',
364-
thumbnail='thumbnail/horizontal-bar.jpg', language='python',
365-
has_thumbnail='true', display_as='basic', order=5,
366-
ipynb= '~notebook_demo/5')
367-
```
368-
369-
```python
370-
371-
```

0 commit comments

Comments
 (0)