在 plotly.express 中隐藏 select 堆积条文本注释
Hide select stacked bar text annotation in plotly.express
import pandas as pd
import plotly.express as px
df1 = pd.DataFrame()
df1['x'] = ['Product A', 'Product B', 'Product C']
df1['z'] = ['T1','T1','T1']
df1['y'] = [20, 14, 23]
df2 = pd.DataFrame()
df2['x'] = ['Product A', 'Product B', 'Product C']
df2['z'] = ['T2','T2','T2']
df2['y'] = [40, 10, 55]
df = df1.append(df2)
fig = px.bar(df,
y="x",
x="y",
text='y',
color='z',barmode='stack')
fig.show()
我只想显示 T1 的标签,保持在 plotly.express
框架内,因为添加 facet_col
功能很容易。
当前结果如下。我想删除 T2(红色)的条形标签,只保留 T1 值的标签。
您可以使用:
fig.for_each_trace(lambda t: t.update(text = []) if t.name not in ['T1'] else ())
并得到:
完整代码:
import pandas as pd
import plotly.express as px
df1 = pd.DataFrame()
df1['x'] = ['Product A', 'Product B', 'Product C']
df1['z'] = ['T1','T1','T1']
df1['y'] = [20, 14, 23]
df2 = pd.DataFrame()
df2['x'] = ['Product A', 'Product B', 'Product C']
df2['z'] = ['T2','T2','T2']
df2['y'] = [40, 10, 55]
df = df1.append(df2)
fig = px.bar(df,
y="x",
x="y",
text='y',
color='z',barmode='stack')
fig.show()
# fig.for_each_trace(lambda t: print(t))
fig.for_each_trace(lambda t: t.update(text = []) if t.name not in ['T1'] else ())
fig.show()
import pandas as pd
import plotly.express as px
df1 = pd.DataFrame()
df1['x'] = ['Product A', 'Product B', 'Product C']
df1['z'] = ['T1','T1','T1']
df1['y'] = [20, 14, 23]
df2 = pd.DataFrame()
df2['x'] = ['Product A', 'Product B', 'Product C']
df2['z'] = ['T2','T2','T2']
df2['y'] = [40, 10, 55]
df = df1.append(df2)
fig = px.bar(df,
y="x",
x="y",
text='y',
color='z',barmode='stack')
fig.show()
我只想显示 T1 的标签,保持在 plotly.express
框架内,因为添加 facet_col
功能很容易。
当前结果如下。我想删除 T2(红色)的条形标签,只保留 T1 值的标签。
您可以使用:
fig.for_each_trace(lambda t: t.update(text = []) if t.name not in ['T1'] else ())
并得到:
完整代码:
import pandas as pd
import plotly.express as px
df1 = pd.DataFrame()
df1['x'] = ['Product A', 'Product B', 'Product C']
df1['z'] = ['T1','T1','T1']
df1['y'] = [20, 14, 23]
df2 = pd.DataFrame()
df2['x'] = ['Product A', 'Product B', 'Product C']
df2['z'] = ['T2','T2','T2']
df2['y'] = [40, 10, 55]
df = df1.append(df2)
fig = px.bar(df,
y="x",
x="y",
text='y',
color='z',barmode='stack')
fig.show()
# fig.for_each_trace(lambda t: print(t))
fig.for_each_trace(lambda t: t.update(text = []) if t.name not in ['T1'] else ())
fig.show()