Skip to content

Commit 0634067

Browse files
more details about bar text formatting
1 parent d8d0e7e commit 0634067

File tree

2 files changed

+120
-25
lines changed

2 files changed

+120
-25
lines changed

Diff for: doc/python/bar-charts.md

+94-15
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,9 @@ jupyter:
3737

3838
[Plotly Express](/python/plotly-express/) is the easy-to-use, high-level interface to Plotly, which [operates on a variety of types of data](/python/px-arguments/) and produces [easy-to-style figures](/python/styling-plotly-express/).
3939

40-
With `px.bar`, each row of the DataFrame is represented as a rectangular mark.
40+
With `px.bar`, **each row of the DataFrame is represented as a rectangular mark**. To aggregate multiple data points into the same rectangular mark, please refer to the [histogram documentation](/python/histograms).
41+
42+
In the example below, there is only a single row of data per year, so a single bar is displayed per year.
4143

4244
```python
4345
import plotly.express as px
@@ -98,21 +100,32 @@ snippet_url = 'https://dash-gallery.plotly.host/python-docs-dash-snippets/'
98100
IFrame(snippet_url + 'bar-charts', width='100%', height=630)
99101
```
100102

101-
### Customized bar charts with Plotly Express
103+
### Colored Bars
102104

103105
The bar plot can be customized using keyword arguments, for example to use [continuous color](https://plotly.com/python/colorscales/), as below, or [discrete color](/python/discrete-color/), as above.
104106

105107
```python
106108
import plotly.express as px
107-
data = px.data.gapminder()
108109

109-
data_canada = data[data.country == 'Canada']
110-
fig = px.bar(data_canada, x='year', y='pop',
110+
df = px.data.gapminder().query("country == 'Canada'")
111+
fig = px.bar(df, x='year', y='pop',
111112
hover_data=['lifeExp', 'gdpPercap'], color='lifeExp',
112113
labels={'pop':'population of Canada'}, height=400)
113114
fig.show()
114115
```
115116

117+
```python
118+
import plotly.express as px
119+
120+
df = px.data.gapminder().query("continent == 'Oceania'")
121+
fig = px.bar(df, x='year', y='pop',
122+
hover_data=['lifeExp', 'gdpPercap'], color='country',
123+
labels={'pop':'population of Canada'}, height=400)
124+
fig.show()
125+
```
126+
127+
### Stacked vs Grouped Bars
128+
116129
When several rows share the same value of `x` (here Female or Male), the rectangles are stacked on top of one another by default.
117130

118131
```python
@@ -133,21 +146,36 @@ fig = px.bar(df, x="sex", y="total_bill",
133146
fig.show()
134147
```
135148

136-
*New in v5.0*
149+
### Aggregating into Single Colored Bars
137150

151+
As noted above `px.bar()` will result in **one rectangle drawn per row of input**. This can sometimes result in a striped look as in the examples above. To combine these rectangles into one per color per position, you can use `px.histogram()`, which has [its own detailed documentation page](/python/histogram).
138152

139-
Bar charts afford the use of [patterns (also known as hatching or texture)](/python/pattern-hatching-texture/) in addition to color:
153+
> `px.bar` and `px.histogram` are designed to be nearly interchangeable in their call signatures, so as to be able to switch between aggregated and disaggregated bar representations.
140154
141155
```python
142156
import plotly.express as px
143-
df = px.data.medals_long()
157+
df = px.data.tips()
158+
fig = px.histogram(df, x="sex", y="total_bill",
159+
color='smoker', barmode='group',
160+
height=400)
161+
fig.show()
162+
```
144163

145-
fig = px.bar(df, x="medal", y="count", color="nation",
146-
pattern_shape="nation", pattern_shape_sequence=[".", "x", "+"])
164+
`px.histogram()` will aggregate `y` values by summing them by default, but the `histfunc` argument can be used to set this to `avg` to create what is sometimes called a "barplot" which summarizes the central tendency of a dataset, rather than visually representing the totality of the dataset.
165+
166+
> Warning: when using `histfunc`s other than `"sum"` or `"count"` it can be very misleading to use a `barmode` other than `"group"`, as stacked bars in effect represent the sum of the bar heights, and summing averages is rarely a reasonable thing to visualize.
167+
168+
```python
169+
import plotly.express as px
170+
df = px.data.tips()
171+
fig = px.histogram(df, x="sex", y="total_bill",
172+
color='smoker', barmode='group',
173+
histfunc='avg',
174+
height=400)
147175
fig.show()
148176
```
149177

150-
#### Bar Charts with Text
178+
### Bar Charts with Text
151179

152180
*New in v5.5*
153181

@@ -161,7 +189,60 @@ fig = px.bar(df, x="medal", y="count", color="nation", text_auto=True)
161189
fig.show()
162190
```
163191

164-
#### Facetted subplots
192+
The `text` argument can be used to display arbitrary text on the bars:
193+
194+
```python
195+
import plotly.express as px
196+
df = px.data.medals_long()
197+
198+
fig = px.bar(df, x="medal", y="count", color="nation", text="nation")
199+
fig.show()
200+
```
201+
202+
By default, Plotly will scale and rotate text labels to maximize the number of visible labels, which can result in a variety of text angles and sizes and positions in the same figure. The `textfont`, `textposition` and `textangle` trace attributes can be used to control these.
203+
204+
Here is an example of the default behavior:
205+
206+
```python
207+
import plotly.express as px
208+
209+
df = px.data.gapminder().query("continent == 'Europe' and year == 2007 and pop > 2.e6")
210+
fig = px.bar(df, y='pop', x='country', text_auto='.2s',
211+
title="Default: various text sizes, positions and angles")
212+
fig.show()
213+
```
214+
215+
Here is the same data with less variation in text formatting. Note that `textfont_size` will set the *maximum* size. The `layout.uniformtext` attribute can be used to guarantee that all text labels are the same size. See the [documentation on text and annotations](/python/text-and-annotations/) for details.
216+
217+
The `cliponaxis` attribute is set to `False` in the example below to ensure that the outside text on the tallest bar is allowed to render outside of the plotting area.
218+
219+
```python
220+
import plotly.express as px
221+
222+
df = px.data.gapminder().query("continent == 'Europe' and year == 2007 and pop > 2.e6")
223+
fig = px.bar(df, y='pop', x='country', text_auto='.2s',
224+
title="Controlled text sizes, positions and angles")
225+
fig.update_traces(textfont_size=12, textangle=0, textposition="outside", cliponaxis=False)
226+
fig.show()
227+
```
228+
229+
### Pattern Fills
230+
231+
*New in v5.0*
232+
233+
234+
Bar charts afford the use of [patterns (also known as hatching or texture)](/python/pattern-hatching-texture/) in addition to color:
235+
236+
```python
237+
import plotly.express as px
238+
df = px.data.medals_long()
239+
240+
fig = px.bar(df, x="medal", y="count", color="nation",
241+
pattern_shape="nation", pattern_shape_sequence=[".", "x", "+"])
242+
fig.show()
243+
```
244+
245+
### Facetted subplots
165246

166247
Use the keyword arguments `facet_row` (resp. `facet_col`) to create facetted subplots, where different rows (resp. columns) correspond to different values of the dataframe column specified in `facet_row`.
167248

@@ -175,9 +256,7 @@ fig = px.bar(df, x="sex", y="total_bill", color="smoker", barmode="group",
175256
fig.show()
176257
```
177258

178-
To learn more, see the _link to px.bar reference page_.
179-
180-
#### Basic Bar Chart with plotly.graph_objects
259+
#### Basic Bar Charts with plotly.graph_objects
181260

182261
If Plotly Express does not provide a good starting point, it is also possible to use [the more generic `go.Bar` class from `plotly.graph_objects`](/python/graph-objects/).
183262

Diff for: doc/python/text-and-annotations.md

+26-10
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ jupyter:
55
text_representation:
66
extension: .md
77
format_name: markdown
8-
format_version: '1.2'
9-
jupytext_version: 1.6.0
8+
format_version: '1.3'
9+
jupytext_version: 1.13.4
1010
kernelspec:
1111
display_name: Python 3
1212
language: python
@@ -20,7 +20,7 @@ jupyter:
2020
name: python
2121
nbconvert_exporter: python
2222
pygments_lexer: ipython3
23-
version: 3.7.6
23+
version: 3.8.11
2424
plotly:
2525
description: How to add text labels and annotations to plots in python.
2626
display_as: file_settings
@@ -116,16 +116,32 @@ snippet_url = 'https://dash-gallery.plotly.host/python-docs-dash-snippets/'
116116
IFrame(snippet_url + 'text-and-annotations', width='100%', height=630)
117117
```
118118

119-
### Controlling text fontsize with uniformtext
119+
### Controlling Text Size with `uniformtext`
120120

121-
For the [pie](/python/pie-charts), [bar](/python/bar-charts), [sunburst](/python/sunburst-charts) and [treemap](/python/treemap-charts) traces, it is possible to force all the text labels to have the same size thanks to the `uniformtext` layout parameter. The `minsize` attribute sets the font size, and the `mode` attribute sets what happens for labels which cannot fit with the desired fontsize: either `hide` them or `show` them with overflow.
121+
For the [pie](/python/pie-charts), [bar](/python/bar-charts)-like, [sunburst](/python/sunburst-charts) and [treemap](/python/treemap-charts) traces, it is possible to force all the text labels to have the same size thanks to the `uniformtext` layout parameter. The `minsize` attribute sets the font size, and the `mode` attribute sets what happens for labels which cannot fit with the desired fontsize: either `hide` them or `show` them with overflow.
122+
123+
124+
Here is a bar chart with the default behavior which will scale down text to fit.
122125

123126
```python
124127
import plotly.express as px
125128

126-
df = px.data.gapminder().query("continent == 'Europe' and year == 2007 and pop > 2.e6")
127-
fig = px.bar(df, y='pop', x='country', text='pop')
128-
fig.update_traces(texttemplate='%{text:.2s}', textposition='outside')
129+
df = px.data.gapminder(year=2007)
130+
fig = px.bar(df, x='continent', y='pop', color="lifeExp", text='country',
131+
title="Default behavior: some text is tiny")
132+
fig.update_traces(textposition='inside')
133+
fig.show()
134+
```
135+
136+
Here is the same figure with uniform text applied: the text for all bars is the same size, with a minimum size of 8. Any text at the minimum size which does not fit in the bar is hidden.
137+
138+
```python
139+
import plotly.express as px
140+
141+
df = px.data.gapminder(year=2007)
142+
fig = px.bar(df, x='continent', y='pop', color="lifeExp", text='country',
143+
title="Uniform Text: min size is 8, hidden if can't fit")
144+
fig.update_traces(textposition='inside')
129145
fig.update_layout(uniformtext_minsize=8, uniformtext_mode='hide')
130146
fig.show()
131147
```
@@ -140,9 +156,9 @@ fig.update_layout(uniformtext_minsize=12, uniformtext_mode='hide')
140156
fig.show()
141157
```
142158

143-
### Controlling text fontsize with textfont
159+
### Controlling Maximum Text Size
144160

145-
The `textfont_size` parameter of the the [pie](/python/pie-charts), [bar](/python/bar-charts), [sunburst](/python/sunburst-charts) and [treemap](/python/treemap-charts) traces can be used to set the **maximum font size** used in the chart. Note that the `textfont` parameter sets the `insidetextfont` and `outsidetextfont` parameter, which can also be set independently.
161+
The `textfont_size` parameter of the the [pie](/python/pie-charts), [bar](/python/bar-charts)-like, [sunburst](/python/sunburst-charts) and [treemap](/python/treemap-charts) traces can be used to set the **maximum font size** used in the chart. Note that the `textfont` parameter sets the `insidetextfont` and `outsidetextfont` parameter, which can also be set independently.
146162

147163
```python
148164
import plotly.express as px

0 commit comments

Comments
 (0)