【发布时间】:2020-10-14 06:11:19
【问题描述】:
我是 python 新手,并且很擅长破折号。我看到了在表格中显示水平条形图的代码。 我希望栏根据另一列改变颜色。例如,我想根据“day”列更改“tip”列中条形的颜色。但是我不知道在我的代码中将 if 语句或过滤查询放在哪里,谁能教我怎么做?
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': (
'{{{column}}} >= {min_bound}' +
(' && {{{column}}} < {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)
【问题讨论】:
标签: python if-statement datatable conditional-formatting plotly-dash