Skip to content

Commit 60e3666

Browse files
Merge pull request #2166 from plotly/imshow-xarray
xarray support in imshow
2 parents 0646966 + 21df030 commit 60e3666

File tree

7 files changed

+225
-54
lines changed

7 files changed

+225
-54
lines changed

Diff for: doc/python/datashader.md

+9-21
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.3.1
8+
format_version: '1.2'
9+
jupytext_version: 1.3.0
1010
kernelspec:
1111
display_name: Python 3
1212
language: python
@@ -20,10 +20,9 @@ jupyter:
2020
name: python
2121
nbconvert_exporter: python
2222
pygments_lexer: ipython3
23-
version: 3.6.8
23+
version: 3.7.3
2424
plotly:
25-
description:
26-
How to use datashader to rasterize large datasets, and visualize
25+
description: How to use datashader to rasterize large datasets, and visualize
2726
the generated raster data with plotly.
2827
display_as: scientific
2928
language: python
@@ -98,30 +97,19 @@ fig.show()
9897
```
9998

10099
```python
101-
import plotly.graph_objects as go
100+
import plotly.express as px
102101
import pandas as pd
103102
import numpy as np
104103
import datashader as ds
105104
df = pd.read_parquet('https://raw.githubusercontent.com/plotly/datasets/master/2015_flights.parquet')
106105

107106
cvs = ds.Canvas(plot_width=100, plot_height=100)
108107
agg = cvs.points(df, 'SCHEDULED_DEPARTURE', 'DEPARTURE_DELAY')
109-
x = np.array(agg.coords['SCHEDULED_DEPARTURE'])
110-
y = np.array(agg.coords['DEPARTURE_DELAY'])
111-
112-
# Assign nan to zero values so that the corresponding pixels are transparent
113-
agg = np.array(agg.values, dtype=np.float)
114-
agg[agg<1] = np.nan
115-
116-
fig = go.Figure(go.Heatmap(
117-
z=np.log10(agg), x=x, y=y,
118-
hoverongaps=False,
119-
hovertemplate='Scheduled departure: %{x:.1f}h <br>Depature delay: %{y} <br>Log10(Count): %{z}',
120-
colorbar=dict(title='Count (Log)', tickprefix='1.e')))
121-
fig.update_xaxes(title_text='Scheduled departure')
122-
fig.update_yaxes(title_text='Departure delay')
108+
agg.values = np.log10(agg.values)
109+
fig = px.imshow(agg, origin='lower', labels={'color':'Log10(count)'})
110+
fig.update_traces(hoverongaps=False)
111+
fig.update_layout(coloraxis_colorbar=dict(title='Count', tickprefix='1.e'))
123112
fig.show()
124-
125113
```
126114

127115
```python

Diff for: doc/python/heatmaps.md

+18-4
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,7 @@ jupyter:
3636

3737
### Heatmap with `plotly.express` and `px.imshow`
3838

39-
[Plotly Express](/python/plotly-express/) is the easy-to-use, high-level interface to Plotly. With `px.imshow`, each value of the input array is represented as a heatmap pixel.
40-
41-
`px.imshow` makes opiniated choices for representing heatmaps, such as using square pixels. To override this behaviour, you can use `fig.update_layout` or use the `go.Heatmap` trace from `plotly.graph_objects` as described below.
39+
[Plotly Express](/python/plotly-express/) is the easy-to-use, high-level interface to Plotly, which [operates on "tidy" data](/python/px-arguments/) and produces [easy-to-style figures](/python/styling-plotly-express/). With `px.imshow`, each value of the input array is represented as a heatmap pixel.
4240

4341
For more examples using `px.imshow`, see the [tutorial on displaying image data with plotly](/python/imshow).
4442

@@ -51,6 +49,22 @@ fig = px.imshow([[1, 20, 30],
5149
fig.show()
5250
```
5351

52+
### Customizing the axes and labels on a heatmap
53+
54+
You can use the `x`, `y` and `labels` arguments to customize the display of a heatmap, and use `.update_xaxes()` to move the x axis tick labels to the top:
55+
56+
```python
57+
import plotly.express as px
58+
data=[[1, 25, 30, 50, 1], [20, 1, 60, 80, 30], [30, 60, 1, 5, 20]]
59+
fig = px.imshow(data,
60+
labels=dict(x="Day of Week", y="Time of Day", color="Productivity"),
61+
x=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
62+
y=['Morning', 'Afternoon', 'Evening']
63+
)
64+
fig.update_xaxes(side="top")
65+
fig.show()
66+
```
67+
5468
### Basic Heatmap with `plotly.graph_objects`
5569

5670
If Plotly Express does not provide a good starting point, it is also possible to use the more generic `go.Heatmap` function from `plotly.graph_objects`.
@@ -67,7 +81,7 @@ fig.show()
6781

6882
### Heatmap with Categorical Axis Labels
6983

70-
In this example we also show how to ignore [hovertext](https://plot.ly/python/hover-text-and-formatting/) when we have [missing values](https://plot.ly/python/missing_values) in the data by setting the [hoverongaps](https://plot.ly/python/reference/#heatmap-hoverongaps) to False.
84+
In this example we also show how to ignore [hovertext](https://plot.ly/python/hover-text-and-formatting/) when we have [missing values](https://plot.ly/python/missing_values) in the data by setting the [hoverongaps](https://plot.ly/python/reference/#heatmap-hoverongaps) to False.
7185

7286
```python
7387
import plotly.graph_objects as go

Diff for: doc/python/imshow.md

+61-6
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ jupyter:
66
extension: .md
77
format_name: markdown
88
format_version: '1.2'
9-
jupytext_version: 1.3.0
9+
jupytext_version: 1.3.1
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.3
23+
version: 3.6.8
2424
plotly:
2525
description: How to display image data in Python with Plotly.
2626
display_as: scientific
@@ -74,7 +74,7 @@ fig = px.imshow(img)
7474
fig.show()
7575
```
7676

77-
### Display single-channel 2D image as grayscale
77+
### Display single-channel 2D data as a heatmap
7878

7979
For a 2D image, `px.imshow` uses a colorscale to map scalar data to colors. The default colorscale is the one of the active template (see [the tutorial on templates](/python/templates/)).
8080

@@ -88,6 +88,17 @@ fig.show()
8888

8989
### Choose the colorscale to display a single-channel image
9090

91+
You can customize the [continuous color scale](/python/colorscales/) just like with any other Plotly Express function:
92+
93+
```python
94+
import plotly.express as px
95+
import numpy as np
96+
img = np.arange(100).reshape((10, 10))
97+
fig = px.imshow(img, color_continuous_scale='Viridis')
98+
fig.show()
99+
```
100+
101+
You can use this to make the image grayscale as well:
91102

92103
```python
93104
import plotly.express as px
@@ -97,16 +108,60 @@ fig = px.imshow(img, color_continuous_scale='gray')
97108
fig.show()
98109
```
99110

100-
### Hiding the colorbar when displaying a single-channel image
111+
### Hiding the colorbar and axis labels
101112

102-
See [the tutorial on coloraxis](/python/colorscales/#share-color-axis) for more details on coloraxis.
113+
See the [continuous color](/python/colorscales/) and [cartesian axes](/python/axes/) pages for more details.
103114

104115
```python
105116
import plotly.express as px
106117
from skimage import data
107118
img = data.camera()
108119
fig = px.imshow(img, color_continuous_scale='gray')
109120
fig.update_layout(coloraxis_showscale=False)
121+
fig.update_xaxes(showticklabels=False)
122+
fig.update_yaxes(showticklabels=False)
123+
fig.show()
124+
```
125+
126+
### Customizing the axes and labels on a single-channel image
127+
128+
You can use the `x`, `y` and `labels` arguments to customize the display of a heatmap, and use `.update_xaxes()` to move the x axis tick labels to the top:
129+
130+
```python
131+
import plotly.express as px
132+
data=[[1, 25, 30, 50, 1], [20, 1, 60, 80, 30], [30, 60, 1, 5, 20]]
133+
fig = px.imshow(data,
134+
labels=dict(x="Day of Week", y="Time of Day", color="Productivity"),
135+
x=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
136+
y=['Morning', 'Afternoon', 'Evening']
137+
)
138+
fig.update_xaxes(side="top")
139+
fig.show()
140+
```
141+
142+
### Display an xarray image with px.imshow
143+
144+
[xarrays](http://xarray.pydata.org/en/stable/) are labeled arrays (with labeled axes and coordinates). If you pass an xarray image to `px.imshow`, its axes labels and coordinates will be used for axis titles. If you don't want this behavior, you can pass `img.values` which is a NumPy array if `img` is an xarray. Alternatively, you can override axis titles hover labels and colorbar title using the `labels` attribute, as above.
145+
146+
```python
147+
import plotly.express as px
148+
import xarray as xr
149+
# Load xarray from dataset included in the xarray tutorial
150+
airtemps = xr.tutorial.open_dataset('air_temperature').air.sel(lon=250.0)
151+
fig = px.imshow(airtemps.T, color_continuous_scale='RdBu_r', origin='lower')
152+
fig.show()
153+
```
154+
155+
### Display an xarray image with square pixels
156+
157+
For xarrays, by default `px.imshow` does not constrain pixels to be square, since axes often correspond to different physical quantities (e.g. time and space), contrary to a plain camera image where pixels are square (most of the time). If you want to impose square pixels, set the parameter `aspect` to "equal" as below.
158+
159+
```python
160+
import plotly.express as px
161+
import xarray as xr
162+
airtemps = xr.tutorial.open_dataset('air_temperature').air.isel(time=500)
163+
colorbar_title = airtemps.attrs['var_desc'] + '<br>(%s)'%airtemps.attrs['units']
164+
fig = px.imshow(airtemps, color_continuous_scale='RdBu_r', aspect='equal')
110165
fig.show()
111166
```
112167

@@ -201,7 +256,7 @@ fig.show()
201256
### imshow and datashader
202257

203258
Arrays of rasterized values build by datashader can be visualized using
204-
imshow. See the [plotly and datashader tutorial](/python/datashader/) for
259+
imshow. See the [plotly and datashader tutorial](/python/datashader/) for
205260
examples on how to use plotly and datashader.
206261

207262

Diff for: packages/python/plotly/plotly/express/_doc.py

+3-10
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,6 @@
66
except AttributeError: # python 2
77
getfullargspec = inspect.getargspec
88

9-
# TODO contents of columns
10-
# TODO explain categorical
11-
# TODO handle color
12-
# TODO handle details of box/violin/histogram
13-
# TODO handle details of column selection with `dimensions`
14-
# TODO document "or `None`, default `None`" in various places
15-
# TODO standardize positioning and casing of 'default'
169

1710
colref_type = "str or int or Series or array-like"
1811
colref_desc = "Either a name of a column in `data_frame`, or a pandas Series or array_like object."
@@ -325,11 +318,11 @@
325318
],
326319
title=["str", "The figure title."],
327320
template=[
328-
"or dict or plotly.graph_objects.layout.Template instance",
329-
"The figure template name or definition.",
321+
"str or dict or plotly.graph_objects.layout.Template instance",
322+
"The figure template name (must be a key in plotly.io.templates) or definition.",
330323
],
331324
width=["int (default `None`)", "The figure width in pixels."],
332-
height=["int (default `600`)", "The figure height in pixels."],
325+
height=["int (default `None`)", "The figure height in pixels."],
333326
labels=[
334327
"dict with str keys and str values (default `{}`)",
335328
"By default, column names are used in the figure for axis titles, legend entries and hovers.",

0 commit comments

Comments
 (0)