-
-
Notifications
You must be signed in to change notification settings - Fork 2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(python!): Use Altair in DataFrame.plot #17995
Merged
Merged
Changes from 2 commits
Commits
Show all changes
50 commits
Select commit
Hold shift + click to select a range
9ed8836
feat(python!): Use Altair in DataFrame.plot
MarcoGorelli 00f7413
missing file
MarcoGorelli f0c806f
use ChannelType
MarcoGorelli eaafc23
typing
MarcoGorelli db6d8f7
requirements
MarcoGorelli f1e5906
Merge remote-tracking branch 'upstream/main' into altair
MarcoGorelli 08e09d4
add histogram example to docstring
MarcoGorelli c6e7d6b
update user guide
MarcoGorelli 9a92211
formatting
MarcoGorelli c59780e
cross-version compat
MarcoGorelli 541361b
py38 typing compat
MarcoGorelli 7f51118
py38 typing compat
MarcoGorelli bb6116c
fix minimum version
MarcoGorelli f4b42b1
try setting typing extensions minimum
MarcoGorelli 91a19f8
regular pip install to debug :sunglasses:
MarcoGorelli 5c61982
that worked...what if we put uv back but without compile-bytecode?
MarcoGorelli 8a11760
maybe not
MarcoGorelli f27326d
try putting torch and extra-index-url on the same line
MarcoGorelli f294a1e
inline torch install
MarcoGorelli 2a1cba0
UV_INDEX_STRATEGY
MarcoGorelli b029aed
revert requirements-ci.txt change
MarcoGorelli e19a0b4
need both altair and hvplot in user guide docs
MarcoGorelli db6b59f
another strategy
MarcoGorelli e22550b
maybe a bit of separation was all we needed
MarcoGorelli 6ff8e99
what if we install cython
MarcoGorelli a9861a0
only use extra index url on linux?
MarcoGorelli 8d329e4
include fi
MarcoGorelli c7a31f0
regular old-fashioned pip install
MarcoGorelli f3186b5
revert requirements-ci.txt change
MarcoGorelli dfd25fa
Merge remote-tracking branch 'upstream/main' into altair
MarcoGorelli 5bd4fb4
Merge remote-tracking branch 'upstream/main' into altair
MarcoGorelli 0f5e803
install typing-extensions _before_ the other requirements
MarcoGorelli df98a2e
minor updates
MarcoGorelli 8d786e1
extra comment
MarcoGorelli 4491d83
remove unused type alias
MarcoGorelli fb0438d
Merge remote-tracking branch 'upstream/main' into altair
MarcoGorelli 9266adb
lint
MarcoGorelli 615bc9f
Merge remote-tracking branch 'upstream/main' into altair
MarcoGorelli 6f4d85a
:truck: 1.5.0 => 1.6.0
MarcoGorelli 3942e62
Merge remote-tracking branch 'upstream/main' into altair
MarcoGorelli 4bc052f
wip
MarcoGorelli e043a35
add Series.plot
MarcoGorelli 65fae74
Merge remote-tracking branch 'upstream/main' into altair
MarcoGorelli ec57fb0
add Series.plot
MarcoGorelli 28ac596
add missing page, add `scatter` as alias
MarcoGorelli d5167f1
lint
MarcoGorelli efed5c9
rename, better bar plot example, simplify
MarcoGorelli 381d481
assorted improvements
MarcoGorelli ea018b5
assorted docs and typing improvements
MarcoGorelli 40a0e31
Merge remote-tracking branch 'upstream/main' into altair
MarcoGorelli File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,163 @@ | ||
from __future__ import annotations | ||
|
||
from typing import TYPE_CHECKING, Any | ||
|
||
if TYPE_CHECKING: | ||
import altair as alt | ||
|
||
from polars import DataFrame | ||
|
||
|
||
class Plot: | ||
"""DataFrame.plot namespace.""" | ||
|
||
chart: alt.Chart | ||
|
||
def __init__(self, df: DataFrame) -> None: | ||
import altair as alt | ||
|
||
self.chart = alt.Chart(df) | ||
|
||
def line( | ||
self, | ||
x: str | Any | None = None, | ||
y: str | Any | None = None, | ||
color: str | Any | None = None, | ||
order: str | Any | None = None, | ||
tooltip: str | Any | None = None, | ||
*args: Any, | ||
**kwargs: Any, | ||
) -> alt.Chart: | ||
""" | ||
Draw line plot. | ||
|
||
Polars does not implement plottinng logic itself but instead defers to Altair. | ||
MarcoGorelli marked this conversation as resolved.
Show resolved
Hide resolved
|
||
`df.plot.line(*args, **kwargs)` is shorthand for | ||
`alt.Chart(df).mark_line().encode(*args, **kwargs).interactive()`, | ||
as is intended for convenience - for full customisatibility, use a plotting | ||
library directly. | ||
|
||
.. versionchanged:: 1.4.0 | ||
In prior versions of Polars, HvPlot was the plotting backend. If you would | ||
like to restore the previous plotting functionality, all you need to do | ||
add `import hvplot.polars` at the top of your script and replace | ||
`df.plot` with `df.hvplot`. | ||
|
||
Parameters | ||
---------- | ||
x | ||
Column with x-coordinates of lines. | ||
y | ||
Column with y-coordinates of lines. | ||
color | ||
Column to color lines by. | ||
order | ||
Column to use for order of data points in lines. | ||
tooltip | ||
Columns to show values of when hovering over points with pointer. | ||
*args, **kwargs | ||
Additional arguments and keyword arguments passed to Altair. | ||
|
||
Examples | ||
-------- | ||
>>> from datetime import date | ||
>>> df = pl.DataFrame( | ||
... { | ||
... "date": [date(2020, 1, 2), date(2020, 1, 3), date(2020, 1, 4)] * 2, | ||
... "price": [1, 4, 6, 1, 5, 2], | ||
... "stock": ["a", "a", "a", "b", "b", "b"], | ||
... } | ||
... ) | ||
>>> df.plot.line(x="date", y="price", color="stock") # doctest: +SKIP | ||
""" | ||
encodings = {} | ||
if x is not None: | ||
encodings["x"] = x | ||
if y is not None: | ||
encodings["y"] = y | ||
if color is not None: | ||
encodings["color"] = color | ||
if order is not None: | ||
encodings["order"] = order | ||
if tooltip is not None: | ||
encodings["tooltip"] = tooltip | ||
return ( | ||
self.chart.mark_line() | ||
.encode(*args, **{**encodings, **kwargs}) | ||
.interactive() | ||
) | ||
|
||
def point( | ||
self, | ||
x: str | Any | None = None, | ||
y: str | Any | None = None, | ||
color: str | Any | None = None, | ||
size: str | Any | None = None, | ||
tooltip: str | Any | None = None, | ||
*args: Any, | ||
**kwargs: Any, | ||
) -> alt.Chart: | ||
""" | ||
Draw scatter plot. | ||
|
||
Polars does not implement plottinng logic itself but instead defers to Altair. | ||
MarcoGorelli marked this conversation as resolved.
Show resolved
Hide resolved
|
||
`df.plot.point(*args, **kwargs)` is shorthand for | ||
`alt.Chart(df).mark_point().encode(*args, **kwargs).interactive()`, | ||
as is intended for convenience - for full customisatibility, use a plotting | ||
library directly. | ||
|
||
.. versionchanged:: 1.4.0 | ||
In prior versions of Polars, HvPlot was the plotting backend. If you would | ||
like to restore the previous plotting functionality, all you need to do | ||
add `import hvplot.polars` at the top of your script and replace | ||
`df.plot` with `df.hvplot`. | ||
|
||
Parameters | ||
---------- | ||
x | ||
Column with x-coordinates of points. | ||
y | ||
Column with y-coordinates of points. | ||
color | ||
Column to color points by. | ||
size | ||
Column which determines points' sizes. | ||
tooltip | ||
Columns to show values of when hovering over points with pointer. | ||
*args, **kwargs | ||
Additional arguments and keyword arguments passed to Altair. | ||
|
||
Examples | ||
-------- | ||
>>> df = pl.DataFrame( | ||
... { | ||
... "length": [1, 4, 6], | ||
... "width": [4, 5, 6], | ||
... "species": ["setosa", "setosa", "versicolor"], | ||
... } | ||
... ) | ||
>>> df.plot.point(x="length", y="width", color="species") # doctest: +SKIP | ||
""" | ||
encodings = {} | ||
if x is not None: | ||
encodings["x"] = x | ||
if y is not None: | ||
encodings["y"] = y | ||
if color is not None: | ||
encodings["color"] = color | ||
if size is not None: | ||
encodings["size"] = size | ||
if tooltip is not None: | ||
encodings["tooltip"] = tooltip | ||
return ( | ||
self.chart.mark_point() | ||
.encode(*args, **{**encodings, **kwargs}) | ||
.interactive() | ||
) | ||
|
||
def __getattr__(self, attr: str, *args: Any, **kwargs: Any) -> alt.Chart: | ||
method = self.chart.getattr(f"mark_{attr}", None) | ||
if method is None: | ||
msg = "Altair has no method 'mark_{attr}'" | ||
raise AttributeError(msg) | ||
return method().encode(*args, **kwargs).interactive() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hi @dangotbanned - may I ask for your input here please?
Thanks 🙏
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the ping, happy to help where I can @MarcoGorelli
Couple of resources up top that I think could be useful:
Will respond each question in another comment 👍
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
1
Can't speak for everyone, but for a reduced selection:
Looking at hvPlot, there are a few methods/chart types I'd need to do some digging to work out the equivalent in
altair
(if there is one).However, my suggestion would be using the names defined there, both for compatibility when switching backends and to reduce the number of methods.
Examples
Haven't covered everything here, but it's a start:
hvPlotTabular
->altair.Chart
(bar|barh)
->mark_bar
box
->mark_boxplot
scatter
->mark_(circle|point|square|image|text)
labels
->mark_text
points
->mark_point
line
->mark_(line|trail)
(polygons|paths)
->mark_geoshape
(area|heatmap)
->mark_area
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
2
I might update this later after thinking on it some more.
Yeah they've been there since
5.2.0
but will be improved foraltair>=5.4.0
with https://github.com/vega/altair/blob/main/altair/vegalite/v5/schema/_typing.pyFor
altair
the model is quite different tomatplotlib
-style functions, but.encode()
would be where to start.Something like:
I wouldn't worry about any
altair
-specific types here.Spelling them out won't have an impact on attribute access of the result
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
3
For typing @binste but really anyone from vega/altair#3452 I think would be interested (time-permitting)
@mattijn, @joelostblom, @jonmmease