python-3.x - 删除重复的图例条形图 matplotlib
问题描述
我想编辑我的图例,使其仅在我使用 for 循环创建条形图时显示标签。如何删除重复的图例?它应该只显示周和月一次
这段代码给了我下面的图表
fig, ax = plt.subplots(figsize = (10,6))
ax.set(xlim=(0,6))
ax.set(ylim=(0,150))
ax.set_xticklabels(edgeslist)
for i in range(6):
plt.bar(x = i, data = classw.iloc[:,i],
height = len(classw.iloc[:,i]) - classw.iloc[:,i].isna().sum(),
color = (0.91, 0.1, 0.4, 1), label = 'week',
align = 'edge', width = -0.4)
plt.bar(x = i, data = classm.iloc[:,i],
height = len(classm.iloc[:,i]) - classm.iloc[:,i].isna().sum(),
color = 'blue', label = 'month',
align = 'edge', width = 0.4)
plt.legend()
解决方案
方法 1只有满足条件,才能在循环内设置图例:
fig, ax = plt.subplots(figsize = (10,6))
ax.set(xlim=(0,6))
ax.set(ylim=(0,150))
ax.set_xticklabels(edgeslist)
for i in range(6):
plt.bar(x = i, data = classw.iloc[:,i],
height = len(classw.iloc[:,i]) - classw.iloc[:,i].isna().sum(),
color = (0.91, 0.1, 0.4, 1), label = 'week',
align = 'edge', width = -0.4)
plt.bar(x = i, data = classm.iloc[:,i],
height = len(classm.iloc[:,i]) - classm.iloc[:,i].isna().sum(),
color = 'blue', label = 'month',
align = 'edge', width = 0.4)
if i==0:
ax.legend()
方法2
你可以创建一个list
带有标签的名字。您将None
只设置一个值,然后在绘图代码中,您以这种方式索引标签列表。
fig, ax = plt.subplots(figsize = (10,6))
ax.set(xlim=(0,6))
ax.set(ylim=(0,150))
ax.set_xticklabels(edgeslist)
label_week = [None]*6
label_week[5] = 'week'
label_month = [None]*6
label_month[5] = 'month'
for i in range(6):
plt.bar(x = i, data = [1, 2, 5, 6, 0, 1],
height = 5,
color = (0.91, 0.1, 0.4, 1), label = label_week[i],
align = 'edge', width = -0.4)
plt.bar(x = i, data = [1, 2, 5, 6, 0, 1],
height = 6,
color = 'blue', label = label_month[i],
align = 'edge', width = 0.4)
plt.legend()
希望能帮助到你。
推荐阅读
- flutter - 如何转换,替换飞镖中的字符串
- qt - 如何在 QML、Qt 中捕获没有鼠标区域的鼠标滚轮移动?
- c# - WPF ComboBox 忽略绑定
- mule - 如何在 dataweave 中使用 Excel 作为查找
- laravel - 我如何才能像 Laravel 中的 dd() 函数一样将变量数据作为字符串获取?
- authentication - Keycloak 是否支持某种形式的中间人身份验证?
- java - CloudSDK 能否帮助使用仅在运行时才知道的 OData 实体类型?
- javascript - ChartJS 根据日期更改显示的数据?
- visual-studio - 如何使用新项目格式将文件夹的文件标记为带有通配符的嵌入式资源?
- ios - 如何让 AKSequencer 切换声音字体?