如何按A列值对两个Plotly横向条形图进行排序?
解决横向条形图按指定列排序的问题
以下两种方法可以让两个子图的国家均按'A'列的值排序:
方法1:提前对数据集排序
先将DataFrame按'A'列的值排序,直接使用排序后的数据集绘图,两个子图会自动沿用统一的国家顺序。
from plotly.subplots import make_subplots import plotly.graph_objects as go import pandas as pd my_data = pd.DataFrame.from_dict({ 'Countries':['Australia', 'Canada', 'China', 'Netherlands'], 'A':[1.89,1.45,1.22,0.94], 'B':[0.8,1,1.45,1.6] }) # 按'A'列升序排序,改为ascending=False可实现降序 sorted_data = my_data.sort_values(by='A', ascending=True) fig = make_subplots(rows=1, cols=2) fig.add_trace( go.Bar( x=sorted_data['A'], y=sorted_data['Countries'], orientation='h', text = sorted_data['A'], name = 'A'), row=1, col=1 ) fig.add_trace( go.Bar( x=sorted_data['B'], y=sorted_data['Countries'], orientation='h', text = sorted_data['B'], name = 'B'), row=1, col=2 ) fig.update_layout(height=600, width=1000, title_text="Side By Side Subplots") fig.show()
方法2:手动指定y轴排序规则
如果不想修改原始数据集,可以通过设置两个子图y轴的categoryarray参数,强制指定按'A'列排序后的国家列表。
from plotly.subplots import make_subplots import plotly.graph_objects as go import pandas as pd my_data = pd.DataFrame.from_dict({ 'Countries':['Australia', 'Canada', 'China', 'Netherlands'], 'A':[1.89,1.45,1.22,0.94], 'B':[0.8,1,1.45,1.6] }) # 获取按'A'列升序排序的国家列表 sorted_countries = my_data.sort_values(by='A', ascending=True)['Countries'].tolist() fig = make_subplots(rows=1, cols=2) fig.add_trace( go.Bar( x=my_data['A'], y=my_data['Countries'], orientation='h', text = my_data['A'], name = 'A'), row=1, col=1 ) fig.add_trace( go.Bar( x=my_data['B'], y=my_data['Countries'], orientation='h', text = my_data['B'], name = 'B'), row=1, col=2 ) # 分别设置两个子图的y轴排序规则 fig.update_layout( height=600, width=1000, title_text="Side By Side Subplots", yaxis={'categoryarray': sorted_countries}, # 第一个子图y轴 yaxis2={'categoryarray': sorted_countries} # 第二个子图y轴 ) fig.show()
原代码失效原因
你之前设置的yaxis={'categoryorder':'total ascending'}仅对第一个子图的y轴生效,且total ascending是按当前子图的数值总和排序,并非按'A'列的值排序;第二个子图的y轴是yaxis2,未设置排序规则,因此保持原始数据顺序。
内容的提问来源于stack exchange,提问作者Nico
相关产品推荐
相关产品推荐

