I am new to python and plotly dash. I saw the code that displays horizontal bar charts within the table. I want the bar to change color depending on another column. For example, I want to change the color of the bar in column "tip" depending on "day" column. But I don't know where to put the if statement or filter query in my code, can anyone teach me how to do it?
import dash
import dash_table
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/tips.csv')
def data_bars(df, column):
n_bins = 100
bounds = [i * (1.0 / n_bins) for i in range(n_bins + 1)]
ranges = [
((df[column].max() - df[column].min()) * i) + df[column].min()
for i in bounds
]
styles = []
for i in range(1, len(bounds)):
min_bound = ranges[i - 1]
max_bound = ranges[i]
max_bound_percentage = bounds[i] * 100
styles.append({
'if': {
'filter_query': (
'} >= {min_bound}' +
(' && } < {max_bound}' if (i < len(bounds) - 1) else '')
).format(column=column, min_bound=min_bound, max_bound=max_bound),
'column_id': column
},
'background': (
"""
linear-gradient(90deg,
#0074D9 0%,
#0074D9 {max_bound_percentage}%,
white {max_bound_percentage}%,
white 100%)
""".format(max_bound_percentage=max_bound_percentage)
),
'paddingBottom': 2,
'paddingTop': 2
})
return styles
app = dash.Dash(__name__)
app.layout = dash_table.DataTable(
data=df.to_dict('records'),
sort_action='native',
columns=[{'name': i, 'id': i} for i in df.columns],
style_data_conditional=(
data_bars(df, 'tip')
),
style_cell={
'width': '100px',
'minWidth': '100px',
'maxWidth': '100px',
'overflow': 'hidden',
'textOverflow': 'ellipsis',
},
page_size=20
)
if __name__ == '__main__':
app.run_server(debug=True)
Aucun commentaire:
Enregistrer un commentaire