Plotly平行坐标图技术咨询:离散色条、字体调整及循环绘图异常
解决Plotly平行坐标图的四个问题
问题1:设置离散颜色对应store_index
把store_index转为字符串类型(标记为类别),在px.parallel_coordinates中使用color_discrete_scale指定离散颜色组,这样每个store_index会对应唯一颜色,colorbar也会自动变为离散样式(后续扩展颜色只需增加颜色组元素即可)。
问题2:增大坐标轴标签字体大小
通过fig.update_traces()修改平行坐标的维度配置,直接为每个维度的label_font参数设置字体大小。
问题3:移除store_index和slice_number轴
在px.parallel_coordinates中显式指定dimensions参数,只保留需要展示的jan_sales和feb_sales,多余的轴就不会被渲染出来。
问题4:修正循环中空图/错误的问题
循环内不要直接修改原始的my_df,每次创建临时数据框temp_df来筛选对应slice的数据——否则原始数据会被逐步过滤为空,导致后续循环无数据可用。
完整修正代码
import pandas as pd import numpy as np import plotly.express as px import os path = r"C:\Users\test" # 生成原始数据 my_df = pd.DataFrame() np.random.seed(0) jan_sales = np.random.randint(low=0, high=100, size=75) feb_sales = np.random.randint(low=0, high=100, size=75) store_index = np.arange(1, 4) store_index = np.repeat(store_index, 25) # 转为字符串标记为类别,实现离散颜色映射 store_index = store_index.astype(str) slice_number = np.arange(1, 6) slice_number = np.tile(slice_number, 3) slice_number = np.repeat(slice_number, 5) my_df['jan_sales'] = jan_sales my_df['feb_sales'] = feb_sales my_df['store_index'] = store_index my_df['slice_number'] = slice_number # 定义离散颜色组(可根据需求扩展数量) color_scale = px.colors.qualitative.D3[:3] for slice_num in np.arange(1, 6): # 使用临时数据框,避免修改原始数据 temp_df = my_df.loc[my_df['slice_number'] == slice_num] # 显式指定要展示的维度,排除store_index和slice_number fig = px.parallel_coordinates( temp_df, color="store_index", dimensions=['jan_sales', 'feb_sales'], labels={"jan_sales": "一月销售额", "feb_sales": "二月销售额"}, color_discrete_scale=color_scale ) # 增大坐标轴标签字体大小 fig.update_traces( dimensions=[ dict(label="一月销售额", label_font=dict(size=14)), dict(label="二月销售额", label_font=dict(size=14)) ] ) # 设置标题样式 fig.update_layout( title=dict( text=f'<b>门店月度销售额切片: 切片 {slice_num}</b>', x=0.5, y=0.99, font=dict(family="Arial", size=12, color='#000000') ), # 自定义colorbar标题(可选) coloraxis_colorbar=dict(title="门店编号", title_font=dict(size=12)) ) fig.write_image(os.path.join(path, f'Slice_{slice_num}.png')) fig.show()
内容的提问来源于stack exchange,提问作者Skylimit
相关产品推荐
相关产品推荐

