Изменение цветов в теме графического графика python dash
В настоящее время я создаю свое первое приложение plotly dash и у меня есть вопрос по графическому тематированию: Я хочу использовать доступную тему plotly_dark и только настраивать основные цвета (цвета фона и элемента) под пользовательские значения. Я играл с представленными здесь идеями: https://plotly.com/python/templates/#saving-and-distributing-custom-themes вот так
import plotly.graph_objects as go import plotly.io as pio pio.templates["plotly_dark_custom"] = go.layout.Template( . custom definitions here. ) pio.templates.default = "plotly_dark_custom"
но мне было интересно, есть ли более интуитивный способ, например, построить дочернюю тему из plotly_dark и только переопределить цвета (предоставляя палитру для цветов и определяя новый цвет фона) после этого. Поскольку я очень новичок в Python, мои знания здесь очень ограничены, поэтому я надеюсь, что вы можете дать мне несколько указателей в правильном направлении. Спасибо и дайте мне знать, если мне следует предоставить больше подробностей по этому запросу. Стефан python plotly-dash
Поделиться Источник 24 апреля 2020 в 11:08
4 ответа
По-видимому, он заранее удается переопределить существующие настройки шаблона (только те, которые указываются), когда вы изменяете их с помощью метода update_layout().
fig1.update_layout( plot_bgcolor='rgb(17,17,17)', paper_bgcolor ='rgb(10,10,10)')
Я только что сделал это и это делает работу, без смысла обращаться к шаблону 🙂
Поделиться 23 января 2021 в 23:42
- Получите настройки из plotly_dark (вам нужно сделать это только один раз)
- установите пользовательский шаблон на plotly dark
- обновите пользовательский шаблон в соответствии с вашими потребностями, учитывая вывод с 1.
import plotly.graph_objects as go import plotly.io as pio plotly_template = pio.templates["plotly_dark"] print (plotly_template) pio.templates["plotly_dark_custom"] = pio.templates["plotly_dark"] pio.templates["plotly_dark_custom"].update(< #e.g. you want to change the background to transparent 'paper_bgcolor': 'rgba(0,0,0,0)', 'plot_bgcolor': 'rgba(0,0,0,0)' >)
Вероятно, это не самое элегантное решение, но оно справляется с задачей. Стефан
Поделиться 25 апреля 2020 в 06:59
Я получил ошибку при запуске ответа Стефана, поэтому я подумал, что опубликую то, что в итоге сработало для меня.
# this helps us get the theme settings import plotly.io as plt_io # this is for simple plotting with plotly express import plotly.express as px # create our custom_dark theme from the plotly_dark template plt_io.templates["custom_dark"] = plt_io.templates["plotly_dark"] # set the paper_bgcolor and the plot_bgcolor to a new color plt_io.templates["custom_dark"]['layout']['paper_bgcolor'] = '#30404D' plt_io.templates["custom_dark"]['layout']['plot_bgcolor'] = '#30404D' # you may also want to change gridline colors if you are modifying background plt_io.templates['custom_dark']['layout']['yaxis']['gridcolor'] = '#4f687d' plt_io.templates['custom_dark']['layout']['xaxis']['gridcolor'] = '#4f687d' # load an example dataset to test df = px.data.iris() # create a nice default plotly example figure fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", size='petal_length', hover_data=['petal_width']) # set the template to our custom_dark template fig.layout.template = 'custom_dark' # and voila, we have a modified dark mode figure fig.show()
Поделиться 30 мая 2020 в 05:27
Это решение довольно чистое, на мой взгляд:
import plotly.io as pio import plotly.graph_objects as go pio.templates['custom'] = go.layout.Template( layout_paper_bgcolor='rgba(0,0,0,0)', layout_plot_bgcolor='rgba(0,0,0,0)' ) pio.templates.default = 'plotly+custom'
plotly.express .funnel¶
plotly.express. funnel ( data_frame = None , x = None , y = None , color = None , facet_row = None , facet_col = None , facet_col_wrap = 0 , facet_row_spacing = None , facet_col_spacing = None , hover_name = None , hover_data = None , custom_data = None , text = None , animation_frame = None , animation_group = None , category_orders = None , labels = None , color_discrete_sequence = None , color_discrete_map = None , opacity = None , orientation = None , log_x = False , log_y = False , range_x = None , range_y = None , title = None , template = None , width = None , height = None ) → plotly.graph_objects._figure.Figure ¶
In a funnel plot, each row of data_frame is represented as a rectangular sector of a funnel.
- data_frame (DataFrameorarray-likeordict) – This argument needs to be passed for column names (and not keyword names) to be used. Array-like and dict are transformed internally to a pandas DataFrame. Optional: if missing, a DataFrame gets constructed under the hood using the other arguments.
- x (strorintorSeriesorarray-like) – Either a name of a column in data_frame , or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the x axis in cartesian coordinates. Either x or y can optionally be a list of column references or array_likes, in which case the data will be treated as if it were ‘wide’ rather than ‘long’.
- y (strorintorSeriesorarray-like) – Either a name of a column in data_frame , or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the y axis in cartesian coordinates. Either x or y can optionally be a list of column references or array_likes, in which case the data will be treated as if it were ‘wide’ rather than ‘long’.
- color (strorintorSeriesorarray-like) – Either a name of a column in data_frame , or a pandas Series or array_like object. Values from this column or array_like are used to assign color to marks.
- facet_row (strorintorSeriesorarray-like) – Either a name of a column in data_frame , or a pandas Series or array_like object. Values from this column or array_like are used to assign marks to facetted subplots in the vertical direction.
- facet_col (strorintorSeriesorarray-like) – Either a name of a column in data_frame , or a pandas Series or array_like object. Values from this column or array_like are used to assign marks to facetted subplots in the horizontal direction.
- facet_col_wrap (int) – Maximum number of facet columns. Wraps the column variable at this width, so that the column facets span multiple rows. Ignored if 0, and forced to 0 if facet_row or a marginal is set.
- facet_row_spacing (float between 0 and 1) – Spacing between facet rows, in paper units. Default is 0.03 or 0.0.7 when facet_col_wrap is used.
- facet_col_spacing (float between 0 and 1) – Spacing between facet columns, in paper units Default is 0.02.
- hover_name (strorintorSeriesorarray-like) – Either a name of a column in data_frame , or a pandas Series or array_like object. Values from this column or array_like appear in bold in the hover tooltip.
- hover_data (str, orlist of strorint, orSeriesorarray-like, ordict) – Either a name or list of names of columns in data_frame , or pandas Series, or array_like objects or a dict with column names as keys, with values True (for default formatting) False (in order to remove this column from hover information), or a formatting string, for example ‘:.3f’ or ‘ | %a’ or list-like data to appear in the hover tooltip or tuples with a bool or formatting string as first element, and list-like data to appear in hover as second element Values from these columns appear as extra data in the hover tooltip.
- custom_data (str, orlist of strorint, orSeriesorarray-like) – Either name or list of names of columns in data_frame , or pandas Series, or array_like objects Values from these columns are extra data, to be used in widgets or Dash callbacks for example. This data is not user-visible but is included in events emitted by the figure (lasso selection etc.)
- text (strorintorSeriesorarray-like) – Either a name of a column in data_frame , or a pandas Series or array_like object. Values from this column or array_like appear in the figure as text labels.
- animation_frame (strorintorSeriesorarray-like) – Either a name of a column in data_frame , or a pandas Series or array_like object. Values from this column or array_like are used to assign marks to animation frames.
- animation_group (strorintorSeriesorarray-like) – Either a name of a column in data_frame , or a pandas Series or array_like object. Values from this column or array_like are used to provide object-constancy across animation frames: rows with matching ` animation_group`s will be treated as if they describe the same object in each frame.
- category_orders (dict with str keys and list of str values (default <> )) – By default, in Python 3.6+, the order of categorical values in axes, legends and facets depends on the order in which these values are first encountered in data_frame (and no order is guaranteed by default in Python below 3.6). This parameter is used to force a specific ordering of values per column. The keys of this dict should correspond to column names, and the values should be lists of strings corresponding to the specific display order desired.
- labels (dict with str keys and str values (default <> )) – By default, column names are used in the figure for axis titles, legend entries and hovers. This parameter allows this to be overridden. The keys of this dict should correspond to column names, and the values should correspond to the desired label to be displayed.
- color_discrete_sequence (list of str) – Strings should define valid CSS-colors. When color is set and the values in the corresponding column are not numeric, values in that column are assigned colors by cycling through color_discrete_sequence in the order described in category_orders , unless the value of color is a key in color_discrete_map . Various useful color sequences are available in the plotly.express.colors submodules, specifically plotly.express.colors.qualitative .
- color_discrete_map (dict with str keys and str values (default <> )) – String values should define valid CSS-colors Used to override color_discrete_sequence to assign a specific colors to marks corresponding with specific values. Keys in color_discrete_map should be values in the column denoted by color . Alternatively, if the values of color are valid colors, the string ‘identity’ may be passed to cause them to be used directly.
- opacity (float) – Value between 0 and 1. Sets the opacity for markers.
- orientation (str, one of ‘h’ for horizontal or ‘v’ for vertical.) – (default ‘v’ if x and y are provided and both continous or both categorical, otherwise ‘v’`( ‘h’ ) if `x`(`y ) is categorical and y`(`x ) is continuous, otherwise ‘v’`( ‘h’ ) if only `x`(`y ) is provided)
- log_x (boolean (default False )) – If True , the x-axis is log-scaled in cartesian coordinates.
- log_y (boolean (default False )) – If True , the y-axis is log-scaled in cartesian coordinates.
- range_x (list of two numbers) – If provided, overrides auto-scaling on the x-axis in cartesian coordinates.
- range_y (list of two numbers) – If provided, overrides auto-scaling on the y-axis in cartesian coordinates.
- title (str) – The figure title.
- template (strordictorplotly.graph_objects.layout.Template instance) – The figure template name (must be a key in plotly.io.templates) or definition.
- width (int (default None )) – The figure width in pixels.
- height (int (default None )) – The figure height in pixels.
Funnel plotly как менять цвет фона



Скачай курс
в приложении
Перейти в приложение
Открыть мобильную версию сайта
© 2013 — 2023. Stepik
Наши условия использования и конфиденциальности

Public user contributions licensed under cc-wiki license with attribution required
Замысел: Как изменить цвет фона каждого подзамысла?
Я пытаюсь создать разные подграфики и хочу, чтобы у каждого подграфика был разный цвет фона. Я использую plotly и это немного усложняет работу. Есть идея? Я думаю, что эквивалент в matplot — face_color или что-то вроде этого.
fig = make_subplots(rows=1, cols=2) fig.add_trace( go.Scatter( x=list(range(sample_points)), y=data_gx.iloc[scene], name='X-axis', line=dict(color='green', width=2) ), row=1, col=1 ) fig.add_trace( go.Scatter( x=list(range(sample_points)), y=data_ax.iloc[scene], name='X-axis', line=dict(color='green', width=2) ), row=1, col=2 )
Поделиться Источник 06 мая 2020 в 08:59
4 ответа
К сожалению, все еще не кажется, что вы можете установить разные цвета фона для разных подграфиков напрямую:
Цвет фона установлен в макете для фигуры: plot_bgcolor=’rgb(245,245,240)’. В данный момент вы не можете изменить задний фон определенного подграфика.
BUT вы можете свободно размещать фигуры в любом месте на обоих подграфиках, ссылаясь на обе оси x через xref=x и xref=x2 в fig.update_layout(shapes=dict()) . И если вы убедитесь, что настроили несколько других параметров, таких как нулевой и layer=’ниже’ , вы получите довольно хороший результат:

Полный код:
# imports from plotly.subplots import make_subplots import plotly.graph_objects as go import pandas as pd import numpy as np # data df = pd.DataFrame(, 'A': , 'B': , 'C': >) # set up plotly figure fig = make_subplots(1,2) # add first bar trace at row = 1, col = 1 fig.add_trace(go.Bar(x=df['Index'], y=df['A'], name='A', marker_color = 'green', opacity=0.4, marker_line_color='rgba(0,0,0,0)', marker_line_width=2), row = 1, col = 1) # add first scatter trace at row = 1, col = 1 fig.add_trace(go.Scatter(x=df['Index'], y=df['B'], line=dict(color='red'), name='B'), row = 1, col = 1) # add first bar trace at row = 1, col = 2 fig.add_trace(go.Bar(x=df['Index'], y=df['C'], name='C', marker_color = 'green', opacity=0.4, marker_line_color='rgba(0,0,0,0)', marker_line_width=2), row = 1, col = 2) fig.update_layout(plot_bgcolor='rgba(0,0,0,0)') # Define gridlines and zerolines # => an invisible zerolines looks better # in this scenario fig.update_layout(xaxis=dict(showgrid=False, zeroline=False), yaxis=dict(showgrid=True, zeroline=False), xaxis2=dict(showgrid=False, zeroline=False), yaxis2=dict(showgrid=True, zeroline=False), ) fig.update_layout( shapes=[ # 1st highlight during Feb 4 - Feb 6 dict( type="rect", xref="x", yref="paper", x0=df['Index'].iloc[0]-1, y0=-0.001, x1=df.index[-1]+2, y1=1, fillcolor="steelblue", opacity=0.5, layer="below", line_width=0, ), # 2nd highlight during Feb 20 - Feb 23 dict( type="rect", xref="x2", yref="paper", x0=df['Index'].iloc[0]-1, y0=-0.001, x1=df.index[-1]+2, y1=1, fillcolor="firebrick", opacity=0.5, layer="below", line_width=0, ) ] ) fig.show()
Поделиться 06 мая 2020 в 10:08
fig.update_layout(plot_bgcolor = "white") fig.show()