要标注和操作柱状堆叠图中的每个堆叠栏,你可以使用以下代码示例:
import matplotlib.pyplot as plt
# 生成示例数据
categories = ['A', 'B', 'C', 'D']
data = {
'Group 1': [4, 3, 2, 1],
'Group 2': [2, 3, 4, 1],
'Group 3': [1, 2, 3, 4]
}
# 绘制柱状堆叠图
fig, ax = plt.subplots()
bar_width = 0.35
bar_positions = list(range(len(categories)))
for group, values in data.items():
ax.bar(bar_positions, values, bar_width, label=group)
bar_positions = [pos + bar_width for pos in bar_positions]
# 标注每个堆叠栏的数值
for rect in ax.patches:
height = rect.get_height()
ax.annotate(f"{height}", xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3), textcoords="offset points",
ha='center', va='bottom')
# 操作每个堆叠栏
def on_bar_click(event):
for rect in ax.patches:
if rect.contains(event)[0]:
# 在这里编写对特定堆叠栏的操作
print("You clicked on a bar!")
fig.canvas.mpl_connect('button_press_event', on_bar_click)
# 显示图例和图表
ax.legend()
plt.show()
这段代码首先生成了示例数据,然后使用ax.bar()
函数绘制了柱状堆叠图。接下来,使用ax.annotate()
函数标注了每个堆叠栏的数值。最后,定义了一个on_bar_click()
函数,用于处理对柱状堆叠图中特定堆叠栏的操作。通过调用fig.canvas.mpl_connect()
函数,将鼠标点击事件与on_bar_click()
函数连接起来。最后,使用ax.legend()
函数显示图例,并调用plt.show()
显示图表。
你可以根据自己的需求修改代码中的数据和操作逻辑。
上一篇:标注FacetGrid点图
下一篇:标注回归线方程和R^2值