Skip to content
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

Improve plotly style guide #7346

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 48 additions & 14 deletions doc/how_to/styling/plotly.md
Original file line number Diff line number Diff line change
@@ -1,26 +1,24 @@
# Style Plotly Plots

This guide addresses how to style Plotly plots displayed using the [Plotly pane](../../reference/panes/Plotly).
This guide demonstrates how to style Plotly plots using the [Plotly pane](../../reference/panes/Plotly). You can customize your plots with Plotly's built-in templates, available in `plotly.io.templates`. For more details, refer to the [Plotly Templates Guide](https://plotly.com/python/templates/).

Plotly provides a list of built in templates in `plotly.io.templates`. See the [Plotly Templates Guide](https://plotly.com/python/templates/).

The gif below displays an example of what can be achieved with a little styling of the Plotly plot and the `FastListTemplate`.
The GIF below illustrates the possibilities when you style a Plotly plot with `FastGridTemplate`.

![PlotlyStyle.gif](https://assets.holoviews.org/panel/thumbnails/gallery/styles/plotly-styles.gif)

## A Plotly Express plot with a custom theme and accent color
## Creating a Plotly Express Plot with a Custom Theme and Accent Color

In this example we will give the Plotly Express plot a dark theme and a custom accent color.
In this example, you'll apply a dark theme and a custom accent color to a Plotly Express plot.

```{pyodide}
import pandas as pd
import plotly.express as px
import plotly.io as pio

import panel as pn

pn.extension("plotly")

# Sample data
data = pd.DataFrame(
[
("Monday", 7),
Expand All @@ -34,53 +32,89 @@ data = pd.DataFrame(
columns=["Day", "Orders"],
)

# Function to create the plot
def plot(template, color):
fig = px.line(
data,
x="Day",
y="Orders",
template=template,
color_discrete_sequence=(color,),
color_discrete_sequence=[color],
title=f"Template: {template}",
)
fig.update_traces(mode="lines+markers", marker=dict(size=10), line=dict(width=4))
fig.layout.autosize = True
return fig

# Widget for template selection and color picker
templates = sorted(pio.templates)
template = pn.widgets.Select(value="plotly_dark", options=templates, name="Template")
color = pn.widgets.ColorPicker(value="#F08080", name="Color")

# Display the plot and widgets
pn.Column(
pn.Row(template, color),
pn.pane.Plotly(pn.bind(plot, template, color), sizing_mode="stretch_width"),
"**Plotly Templates**: " + ", ".join(templates),
).servable()
```

## A Plotly `go.Figure` plot with dark theme
## Styling a Plotly `go.Figure` Plot with a Dark Theme

In this example we will give the Plotly `go.Figure` plot a dark theme.
This example shows how to apply a dark theme to a Plotly `go.Figure` plot.

```{pyodide}
import pandas as pd
import plotly.graph_objects as go

import panel as pn

pn.extension("plotly")

TEMPLATE = "plotly_dark" # "ggplot2", "seaborn", "simple_white", "plotly", "plotly_white", "plotly_dark", "presentation", "xgridoff", "ygridoff", "gridon", "none"
# Choose a template
TEMPLATE = "plotly_dark"

# Load data for the plot
z_data = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/api_docs/mt_bruno_elevation.csv")

# Create a 3D surface plot
fig = go.Figure(
data=go.Surface(z=z_data.values),
layout=go.Layout(
title="Mt Bruno Elevation",
))
)
)
fig.layout.autosize = True
fig.update_layout(template=TEMPLATE, title=f"Mt Bruno Elevation in a '{TEMPLATE}' template")
fig.update_layout(template=TEMPLATE, title=f"Mt Bruno Elevation in '{TEMPLATE}' template")

# Display the plot
pn.pane.Plotly(fig, height=500, sizing_mode="stretch_width").servable()
```

## Changing the Default Theme in Plotly Express

You can change the default Plotly Express `template` based on the `pn.config.theme` setting:

```python
import plotly.express as px

px.defaults.template = "plotly_dark" if pn.config.theme == "dark" else "plotly_white"
```

## Changing Plotly Template Defaults

For example, you can set `paper_bgcolor` and `plot_bgcolor` to transparent:

```python
import plotly.io as pio

for theme in ["plotly_dark", "plotly_white"]:
pio.templates[theme].layout.paper_bgcolor = 'rgba(0,0,0,0)'
pio.templates[theme].layout.plot_bgcolor = 'rgba(0,0,0,0)'
pio.templates[theme].layout.legend = dict(orientation="h", yanchor="bottom", y=-0.2)
pio.templates[theme].layout.bargap = 0.2
```

## Additional Examples

- [Panel Iris Analysis | PY.CAFE](https://py.cafe/panel-org/panel-iris-analysis).
- [Plotly Style Dashboard | PY.CAFE](https://py.cafe/panel-org/plotly-style-dashboard).
14 changes: 7 additions & 7 deletions examples/reference/panes/Plotly.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"source": [
"## Parameters:\n",
"\n",
"For details on other options for customizing the component see the [layout](../../how_to/layout/index.md) and [styling](../../how_to/styling/index.md) how-to guides.\n",
"For details on other options for customizing the component see the general [layout](../../how_to/layout/index.md) and [styling](../../how_to/styling/index.md) how-to guides as well as the specific [Style Plotly Plots](../../how_to/styling/plotly.md) how-to guide.\n",
"\n",
"### Core\n",
"\n",
Expand Down Expand Up @@ -622,12 +622,12 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"\r\n",
"\r\n",
"### Parent-Child Views\r\n",
"\r\n",
"A common technique for exploring higher-dimensional datasets is the use of Parent-Child views. This approach allows you to employ a top-down method to initially exing thehree most important dimensions in the parent plot. You can then select a subset of the data points and examine them in greater detail and across additional dimensions.\r\n",
"\r\n",
"\n",
"\n",
"### Parent-Child Views\n",
"\n",
"A common technique for exploring higher-dimensional datasets is the use of Parent-Child views. This approach allows you to employ a top-down method to initially exing thehree most important dimensions in the parent plot. You can then select a subset of the data points and examine them in greater detail and across additional dimensions.\n",
"\n",
"Let's create a plot where Box or Lasso selections in the parent plot update a child plot. We will also customize the action bars using the `config` parameter."
]
},
Expand Down
6 changes: 5 additions & 1 deletion panel/io/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -484,7 +484,11 @@ def as_cached(self, key: str, fn: Callable[[], T], ttl: int = None, **kwargs) ->
Note: Keyword arguments must be hashable.
Example:
Pandas Example:
>>> data = pn.state.as_cached('data', pd.read_csv, filepath_or_buffer=DATA_URL)
Copy link
Collaborator Author

@MarcSkovMadsen MarcSkovMadsen Sep 29, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe this example is great to add because pn.read_xyz is probably the most used function to cache. I the filepath_or_buffer name no one can remember.

Function Example:
>>> def load_dataset(name):
>>> # some slow operation that uses name to load a dataset....
Expand Down
Loading