英文:
Can anyone advise on how to apply custom ordering of a legend for pywaffle?
问题
我理解pywaffle接受matplotlib.pyplot.legend
参数的dict形式。我不太清楚如何将这些参数应用于生成一个具有自定义类别顺序的图例。
请问有人可以建议如何更新我的代码以将自定义顺序应用于图例吗?
plt.rcParams["figure.figsize"] = [7, 7]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure(
FigureClass=Waffle,
rows=10,
values=df['values'],
title={'label': '最新数据,2022年', 'loc': 'center'},
labels=list(df.category),
legend={'loc': 'lower center', 'bbox_to_anchor': (.5, -0.1), 'ncol': len(df)},
starting_location='SE',
block_arranging_style='snake',
icons='person', icon_size=32,
)
plt.show()
英文:
I understand that pywaffle accepts parameters of matplotlib.pyplot.legend
in a dict. I'm not really across how to apply these parameters to generate a legend with a custom order of categories.
Can anyone please advise how to update my code to apply a customer order to my legend?
plt.rcParams["figure.figsize"] = [7, 7]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure(
FigureClass=Waffle,
rows=10,
values=df['values'],
title={'label': 'Latest data, 2022', 'loc': 'center'},
labels=list(df.category),
legend={'loc': 'lower center','bbox_to_anchor': (.5, -0.1),'ncol': len(df)},
starting_location='SE',
block_arranging_style='snake',
icons='person', icon_size=32,
)
plt.show()
答案1
得分: 1
图例是按照给定的数值和相应标签的顺序创建的。一旦创建,您可以使用不同的项目顺序再次创建它。
以下是一个示例:
import matplotlib.pyplot as plt
from pywaffle import Waffle
values = [12, 20, 15]
labels = ['twelve', 'twenty', 'fifteen']
legend_dict = {'loc': 'upper center', 'bbox_to_anchor': (.5, -0.01), 'ncol': 3}
fig = plt.figure(
FigureClass=Waffle,
rows=10,
values=values,
title={'label': 'Latest data, 2022', 'loc': 'center'},
labels=labels,
legend=legend_dict,
starting_location='SE',
block_arranging_style='snake',
# icons='person', icon_size=2,
)
handles_dict = {h.get_label(): h for h in fig.axes[0].legend_.legendHandles}
new_label_order = ['fifteen', 'twelve', 'twenty']
new_handles = [handles_dict[lbl] for lbl in new_label_order]
plt.legend(handles=new_handles, **legend_dict)
plt.show()
英文:
The legend is created in the order that the values and corresponding labels are given. Once created, you can create it again with a different ordering of the items.
Here is an example:
import matplotlib.pyplot as plt
from pywaffle import Waffle
values = [12, 20, 15]
labels = ['twelve', 'twenty', 'fifteen']
legend_dict = {'loc': 'upper center', 'bbox_to_anchor': (.5, -0.01), 'ncol': 3}
fig = plt.figure(
FigureClass=Waffle,
rows=10,
values=values,
title={'label': 'Latest data, 2022', 'loc': 'center'},
labels=labels,
legend=legend_dict,
starting_location='SE',
block_arranging_style='snake',
# icons='person', icon_size=2,
)
handles_dict = {h.get_label(): h for h in fig.axes[0].legend_.legendHandles}
new_label_order = ['fifteen', 'twelve', 'twenty']
new_handles = [handles_dict[lbl] for lbl in new_label_order]
plt.legend(handles=new_handles, **legend_dict)
plt.show()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论