In: Computer Science
python 2.7 Dash
How to draw a bar & line & pie chart for below dict data by using Dash?
The value is the percentage of each month. So total will be 100.
{'Mar': 17.973851593144104, 'Feb': 10.540182187664472, 'Sep': 8.200076731097335, 'Apr': 12.080717324339435, 'Jan': 16.118724221364918, 'Nov': 12.29654875876966, 'Dec': 11.378407574427893, 'Oct': 11.411491609192186}
Please provide the python 2.7 code.
Python Code:
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go
app = dash.Dash()
# The given dictionary
dict = {'Mar': 17.973851593144104, 'Feb': 10.540182187664472,
'Sep': 8.200076731097335, 'Apr': 12.080717324339435, 'Jan':
16.118724221364918, 'Nov': 12.29654875876966, 'Dec':
11.378407574427893, 'Oct': 11.411491609192186}
# Extracting the keys from the given dictionary
# i.e. the months
Xvalues = []
for x in dict:
Xvalues.append(x)
# Extracting the values for each month
# from the dictionary
Yvalues = []
for x in dict:
Yvalues.append(dict[x])
# defining the body of the web page
app.layout = html.Div(children=[
html.H1(
children='Graphs',
style={
'textAlign': 'center'
}
),
html.Div(children='Bar Graph', style={
'textAlign':
'center'
}),
# Graph 1: Bar Graph
dcc.Graph(
id='bar',
figure={
'data': [
# using plotly to define the graphs
# x variable contains the months and corresponds
to x axis
# y variable contains the values and corresponds
to y axis
# name matters when there are different types of
data to be compared
go.Bar(x = Xvalues, y = Yvalues, name =
'Month')
]
}
),
html.Div(children='Line Graph', style={
'textAlign':
'center'
}),
# Graph 2: Line Graph
dcc.Graph(
id='line',
figure={
'data': [
# Scatter function is used for both line and
scatter graphs
# the difference is seen depending on the
mode
# if mode = 'lines', a line graph is
displayed
# if mode = 'markers', a scatter graph is
displayed (with dots at the values)
# if mode = 'lines + markers', a line graph,
with dots at the values
go.Scatter(x = Xvalues, y = Yvalues, name =
'Month', mode='markers + lines'),
]
}
),
html.Div(children='Pie Graph', style={
'textAlign':
'center'
}),
dcc.Graph(
id='pie',
figure={
'data': [
# Pie graph
go.Pie(labels=Xvalues, values=Yvalues,
name='Months'),
]
}
)
])
# Running the server in localhost:8050
if __name__ == '__main__':
app.run_server(debug=True)
Web page screenshots:
Bar graph:
Line Graph:
Pie Graph: