-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathplotly-python.qmd
More file actions
70 lines (54 loc) · 2.41 KB
/
plotly-python.qmd
File metadata and controls
70 lines (54 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
---
title: plotly-python
author: "openai gpt-4o"
date: "2024-10-23 16:52:22.554560"
format:
html:
code-tools:
source: https://github.com/quarto-dev/quarto-examples/blob/main/renderings/plotly-python.qmd
---
# Question
How can I draw a violin plot of the Iris data using Plotly?
# Explanation
Plotly is an interactive plotting library that is ideal for creating detailed interactive plots, including violin plots. It is easy to create a violin plot using the `plotly.express` module, which simplifies many common plotting tasks. The Iris dataset, commonly used in machine learning, is built into the `sklearn` library. We will load this dataset, convert it into a suitable format using Pandas, and then plot it using Plotly.
# Code
```{python}
#| echo: false
from quarto import theme_brand_plotly
import plotly.io as pio
pio.templates['light_brand'] = theme_brand_plotly('light-brand.yml')
pio.templates['dark_brand'] = theme_brand_plotly('dark-brand.yml')
```
```{python}
#| echo: false
#| renderings: [light, dark]
# plotly 6.* has three outputs the first time you run it.
# without "foo" you'll get the warning
# (W) need 2 cell-output-display for renderings light,dark; got 3
# and no light/dark treatment
# it seems (?) to be safe to drop "foo"
import plotly.express as px
import pandas as pd
from sklearn.datasets import load_iris
from functools import partial
# Load the iris dataset
iris_data = load_iris()
iris_df = pd.DataFrame(data=iris_data.data, columns=iris_data.feature_names)
iris_df['species'] = pd.Categorical.from_codes(iris_data.target, iris_data.target_names)
plot = px.violin(iris_df, x='species', y='sepal length (cm)', box=True, points="all",
title='Violin Plot of Sepal Length in Iris Dataset')
plot.update_layout(template='light_brand')
display(plot)
plot.update_layout(template='dark_brand')
display(plot)
```
Again!
```{python}
#| echo: false
#| renderings: [light, dark]
plot.update_layout(template='light_brand')
display(plot)
plot.update_layout(template='dark_brand')
display(plot)
```
This code uses `plotly.express` to create a violin plot of the sepal length by species from the Iris dataset. The `sepal length (cm)` is plotted on the Y-axis, with each species on the X-axis. The violin plot provides insights into the distribution of sepal length measurements within each species, along with a box plot overlay and individual measurements as jittered points for detailed data analysis.