如何在Plotly柱状图中实现条形的蓝红交替双色效果
用Plotly Express实现柱状图红蓝交替着色
需求说明
需要创建柱状图,使条形按蓝色、红色、蓝色、红色的交替顺序显示颜色,已在Matplotlib中实现该效果,现需用Plotly Express完成相同功能。现有代码如下:
import pandas as pd import plotly.graph_objects as go import matplotlib.pyplot as plt df_1 = pd.DataFrame(freqfinal, columns=['teller' , 'frequenties']) # df = dataframe, pd staat voor Pandas # Plotly基础实现(未着色) fig = go.Figure() fig.add_trace(go.Bar(x=df_1.teller, y=df_1.frequenties, showlegend= True)) fig.show() # Matplotlib已实现双色交替效果 bar_colors = ['red', 'blue'] ax = df_1['frequenties'].plot(kind='bar', color=bar_colors, title= 'series per 100 trekkingen') # barchart met behulp van matplotlib ax.set_xlabel('volgorde frequenties') #label x-as ax.set_ylabel('serie grootte') # label y-as plt.show()
Plotly Express实现方案
在Plotly Express中,只需生成与数据行数匹配的交替颜色列表,传递给color_discrete_sequence参数即可实现效果。以下是两种简洁的实现方式:
方式一:列表推导式生成交替颜色
import pandas as pd import plotly.express as px df_1 = pd.DataFrame(freqfinal, columns=['teller' , 'frequenties']) # 生成蓝红交替的颜色列表,索引偶数为蓝色,奇数为红色 bar_colors = ['blue' if i % 2 == 0 else 'red' for i in range(len(df_1))] # 绘制柱状图并应用颜色 fig = px.bar( df_1, x='teller', y='frequenties', color_discrete_sequence=bar_colors, title='series per 100 trekkingen', labels={ 'teller': 'volgorde frequenties', 'frequenties': 'serie grootte' } ) fig.show()
方式二:重复颜色序列补全
import pandas as pd import plotly.express as px df_1 = pd.DataFrame(freqfinal, columns=['teller' , 'frequenties']) # 生成重复的蓝红序列,长度匹配数据行数 bar_colors = ['blue', 'red'] * (len(df_1) // 2) # 若数据行数为奇数,补充最后一个蓝色 if len(df_1) % 2 != 0: bar_colors.append('blue') fig = px.bar( df_1, x='teller', y='frequenties', color_discrete_sequence=bar_colors, title='series per 100 trekkingen', labels={ 'teller': 'volgorde frequenties', 'frequenties': 'serie grootte' } ) fig.show()
以上两种方式都能实现和Matplotlib一致的红蓝交替条形着色效果,同时通过labels参数直接设置坐标轴标签,无需额外调用方法。
内容的提问来源于stack exchange,提问作者Eelco Schipperus
相关产品推荐
相关产品推荐

