Dataset
For a barplot, we need a dataset with two columns: one for the categories and one for the values.
Let's create it using pandas
:
import pandas as pd
data = {
'category': ['A', 'B', 'C', 'D', 'E'],
'value': [17, 42, 33, 55, 25]
}
df = pd.DataFrame(data)
df.head()
category | value | |
---|---|---|
0 | A | 17 |
1 | B | 42 |
2 | C | 33 |
3 | D | 55 |
4 | E | 25 |
Barplot with plotly express
The chart is made using using the bar()
function from the plotly.express
module.
We just have to pass the df
object, and specify which column we want to plot. In this case it's the category
and the value
(defined above).
import plotly.express as px
fig = px.bar(
df,
x='category',
y='value'
)
fig.update_traces(marker_color='green')
fig.show()
Now we save it as an html element in order to render it
# save widget to html
fig.write_html(
"../../static/interactiveCharts/582-simple-barplot-plotly-1.html"
)
%%html
<iframe
src="../../interactiveCharts/582-simple-barplot-plotly-1.html"
width="790"
height="700"
title="Barplot with plotly express"
style="border:none">
</iframe>
Barplot with plotly graph object
import plotly.graph_objects as go
data = go.Bar(
x=df['category'],
y=df['value'],
marker_color='red'
)
fig = go.Figure()
fig.add_trace(data)
fig.show()
Now we save it as an html element in order to render it
# save widget to html
fig.write_html(
"../../static/interactiveCharts/582-simple-barplot-plotly-2.html"
)
%%html
<iframe
src="../../interactiveCharts/582-simple-barplot-plotly-2.html"
width="790"
height="700"
title="Barplot with plotly graph object"
style="border:none">
</iframe>
Going further
You might be interested in:
- creating an interactive stacked barplot
- creating an interactive radar chart