Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

python 3.x - Plotly: How to use a built-in colorscale in a pie chart?

I am just trying to learn python. Can someone help to understand how to add px.colors.qualitative.Pastel2 into the below code.

import dash
import dash_core_components as dcc
import dash_html_components as html
import pyodbc
import plotly.offline as pyo
import plotly.graph_objs as go
import pandas as pd
import plotly.express as px

connection = pyodbc.connect('Driver={SQL Server};'
                          'Server=sqlserver;'
                          'Database=mydatabase;'
                          'UID =sa;'
                          'PWD = sa123;')

app = dash.Dash()
sql_data=pd.read_sql_query("select columna, columnb from table", connection)
piechart = go.Pie(labels=sql_data['columna'], values=sql_data['columnb'])

app.layout = html.Div(children=[    
            dcc.Graph(id='example',
            figure={'data': [piechart],
                'layout': {'title': 'PieChart Sample'}
                })
 ])

Thanks

question from:https://stackoverflow.com/questions/65642529/plotly-how-to-use-a-built-in-colorscale-in-a-pie-chart

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As explained in the Plotly documentation you can specify a list of colors as follows:

piechart = go.Pie(labels=sql_data['columna'],
                  values=sql_data['columnb'],
                  marker=dict(colors=px.colors.qualitative.Pastel2))

Note that px.colors.qualitative.Pastel2 is a list of 8 colors, and therefore the color palette will only be applied to the first 8 sectors of the pie chart, while the subsequent sectors will still use the default colors.

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import plotly.express as px
import pandas as pd

sql_data = pd.DataFrame({'columna': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
                         'columnb': [1, 2, 3, 4, 5, 6, 7, 8]})

piechart = go.Pie(labels=sql_data['columna'],
                  values=sql_data['columnb'],
                  marker=dict(colors=px.colors.qualitative.Pastel2))

app = dash.Dash()

app.layout = html.Div(children=[

    dcc.Graph(figure={'data': [piechart],
                      'layout': {'title': 'PieChart Sample',
                                 'legend': {'traceorder': 'reversed'}}})

])

if __name__ == '__main__':
    app.run_server(debug=False, host='127.0.0.1')

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...