使用plotly,如何隐藏特定的颜色代码?

问题描述 投票:0回答:1

我正在绘制一堆不同的系统,但我会将它们分组为仅 2 或 3 种不同的颜色。因此,在下面的示例中,绘图后我还希望能够根据系统的颜色而不仅仅是名称来隐藏或显示系统。那可能吗?那么除了点击“系统4”隐藏那个之外,是否可以点击一个按钮全部隐藏蓝色呢?

enter image description here

import plotly.express as px
import pandas as pd
import numpy as np

# Data
data = {
    "System": ["System 1", "System 1", "System 1", "System 2", "System 2", "System 3", "System 3", "System 3", "System 4", "System 4"],
    "Year": [2020, 2020, 2020, 2021, 2020, 2020, 2020, 2021, 2019, 2021]
}

# Convert to DataFrame
df = pd.DataFrame(data)

# Define color mapping for systems
color_map = {
    "System 1": '#1f77b4',
    "System 2": '#1f77b4',
    "System 3": '#ff7f0e',
    "System 4": '#ff7f0e'
}

max_n = 2022
min_n = 2016
bins = 7
step = (max_n - min_n) / bins

arr_div = np.arange(min_n + step / 2, max_n + step / 2, step=step)
arr_div_r = np.round(arr_div, 0).astype(int)

# Define order of legend
legend_order = ["System 1", "System 2", "System 3", "System 4"]

# Create histogram with Plotly Express and specify custom color sequence
fig = px.histogram(df, x="Year", color="System", category_orders={"System": legend_order}, nbins=bins, barmode='stack', color_discrete_map=color_map)

# Add black border to each bar
fig.update_traces(marker_line_color='black', marker_line_width=2)

# Update layout
fig.update_layout(
    title='Histogram',
    xaxis_title='Year',
    yaxis_title='Amount',
    xaxis=dict(
        tickmode='array',
        tickvals=np.arange(min_n, max_n+1, 1)
    )
)

# Move x-axis tick labels outside the plot area
fig.update_xaxes(ticklabelposition='outside bottom')

# Show plot
fig.show()
python python-3.x plotly plotly-python
1个回答
0
投票

您可以将其添加到底部,就在

fig.show()
:

之前
for trace in fig.data:
    trace['legendgroup'] = trace['marker']['color']
© www.soinside.com 2019 - 2024. All rights reserved.