如何在Python中绘制跟踪资源管理器(&Q)?
问题描述
我需要重新创建一个图-Trace explorer类似于下面在R中创建的图。我希望使用matplotlib,但找不到任何示例或引用来说明如何使用这样的Trace Explorer。有谁能给我指个方向吗?不过,我确实需要能够使用Python来做到这一点。
测试或样本数据
import pandas as pd
data_dict = {"Trace" : [["A-M", "B&M", "B&Q", "BLOG", "BYPAS", "CIM"],
["B&M", "B&Q", "BLOG", "BYPAS"],
["BLOG", "BYPAS", "CIM"],
["A-M", "B&M", "B&Q", "BLOG"]],
"Percentage" : [28.09, 32, 0.98, 18.68]}
data = pd.DataFrame(data_dict)
acronym = {"A-M" : "Alternating Maximization",
"B&M" : "Business & Management",
"B&Q" : "Batch-And-Queue",
"BLOG" : "Buy Locally Owned Group",
"BYPAS" : "Bypass",
"CIM" : "Common Information Model"
}
解决方案
可以使用plt.Rectangle()
创建彩色矩形,使用ax.text
放置文本。
可以有多种变体。以下是一些示例代码,可帮助您入门:
import matplotlib.pyplot as plt
data_dict = {"Trace": [["A-M", "B&M", "B&Q", "BLOG", "BYPAS", "CIM"],
["B&M", "B&Q", "BLOG", "BYPAS"],
["BLOG", "BYPAS", "CIM"],
["A-M", "B&M", "B&Q", "BLOG"]],
"Percentage": [28.09, 32, 0.98, 18.68]}
acronym = {"A-M": "Alternating Maximization",
"B&M": "Business & Management",
"B&Q": "Batch-And-Queue",
"BLOG": "Buy Locally Owned Group",
"BYPAS": "Bypass",
"CIM": "Common Information Model"
}
cmap = plt.cm.get_cmap('rainbow')
color_dict = {acr: cmap((i + 1) / (len(acronym) + 1)) for i, acr in enumerate(acronym)}
fig, ax = plt.subplots(figsize=(12, 4))
percentage_position = max(len(t) for t in data_dict["Trace"]) + 1.1
for row, (trace, percentage) in enumerate(zip(data_dict["Trace"], data_dict["Percentage"]), start=1):
for col, acr in enumerate(trace, start=1):
ax.add_patch(plt.Rectangle((col - 0.5, row - 0.45), 1, 0.9, facecolor=color_dict[acr], edgecolor='black'))
ax.text(col, row, acr, ha='center', va='center')
ax.add_patch(plt.Rectangle((percentage_position - 0.5, row - 0.45), 1, 0.9, facecolor='grey', edgecolor='white'))
ax.text(percentage_position, row, f'{percentage:.2f}%', ha='center', va='center', color='white')
ax.set_xlim(0.5, percentage_position + 0.5)
ax.set_xticks(range(1, int(percentage_position)))
ax.set_ylim(len(data_dict["Trace"]) + 0.45, 0.55) # y-axis is reversed
ax.set_yticks([])
handles = [plt.Rectangle((0, 0), 0, 0, facecolor=color_dict[acr], edgecolor='black', label=acronym[acr])
for acr in acronym]
ax.legend(handles=handles, bbox_to_anchor=[1.02, 1.02], loc='upper left')
for dir in ['left', 'right', 'top']:
ax.spines[dir].set_visible(False)
plt.tight_layout()
plt.show()
相关文章