在mpld3中设置刻度标签

4

我想简单地创建一个条形图,包含一些数据(此处硬编码,但最终我会从文件中读取数据)。目前为止,我已经能够得到条形图,但是我希望属性“特征名称”出现在每个条形下面。现在,我只得到了1到16的数字。我该怎么做才能使每个特征都出现在相应的条形下面呢?

我的代码:

import matplotlib.pyplot as plt
import numpy as np
import mpld3

fig, ax = plt.subplots()

N = 17
feature_name = ('AccountLength','Intlact','Vmailact','Vmailnumber','day minutes','day calls','day charge','evening minutes','evening calls','evening charge','night minutes','night calls','night charge','intl minutes','intl calls','intl charge','cust calls')
importance = (0.0304,0.0835,0.0222,0.0301,0.1434,0.0315,0.1354,0.0677,0.0268,0.0669,0.0386,0.0286,0.0371,0.0417,0.0521,0.0434,0.1197)
ind = np.arange(N)
width = 0.20
rects = ax.bar(ind, importance, width, color = 'r')
ax.grid(color='white', linestyle='solid')

ax.set_title("Why are my customers churning?", size=20)
ax.set_ylabel('Importance in percentage')
ax.set_xlabel('Feature Name')
ax.set_xticklabels( (feature_name) )
labels = (feature_name)
tooltip = mpld3.plugins.PointLabelTooltip(rects, labels=labels)
mpld3.plugins.connect(fig, tooltip)

mpld3.show()

编辑:事实证明,如果我使用plt.show(),我可以看到刻度标签,但当我尝试在mpld3中执行相同操作时,它不起作用。同时想知道为什么工具提示没有显示。


你正在使用哪个版本的 mpld3?你可以尝试使用来自 github 上最新的版本吗? - Abraham D Flaxman
我正在使用最新的版本。 - lordingtar
2个回答

1

我觉得答案来得有些晚了,但也许这可以帮助其他人。

mpld3 包中,将文本设置为刻度标签似乎存在一些问题,但是当我绘制某些数据到特定范围值时,我能够做到这一点,然后将刻度设置为这个范围,并最终将刻度标签设置为所需的标签。

from matplotlib import pyplot as plt
import numpy as np
import mpld3

fig, ax = plt.subplots()

feature_name = ('AccountLength','Intlact','Vmailact','Vmailnumber','day minutes','day calls','day charge','evening minutes','evening calls','evening charge','night minutes','night calls','night charge','intl minutes','intl calls','intl charge','cust calls')
importance = (0.0304,0.0835,0.0222,0.0301,0.1434,0.0315,0.1354,0.0677,0.0268,0.0669,0.0386,0.0286,0.0371,0.0417,0.0521,0.0434,0.1197)
ind = range(1, len(feature_name)+1)
width = 0.20

rects = ax.bar(ind, importance, width, color = 'r')

ax.grid(linestyle='solid')
ax.set_title("Why are my customers churning?", size=20)
ax.set_ylabel('Importance in percentage')
ax.set_xlabel('Feature Name')
ax.set_xticks(ind)
ax.set_xticklabels(feature_name)

mpld3.show()

结果:

mpld3 ticklabels example

有一个与刻度旋转相关的额外条目(也不受 mpld3 支持)。 可能需要编写自定义插件才能实现此功能。 如果有人需要这个功能,则我会更新答案。


我将你的代码复制粘贴到我的笔记本中,但在X轴上得到的是数字而不是文本。我正在使用mpld3 0.5.2版本。我想知道你的设置有什么不同,以便获得文本标签。 - bhomass

0

在mpld3中不支持设置刻度标签和位置。请参见问题22

工具提示不会出现,因为PointLabelTooltip()函数接受matplotlib Collection或Line2D对象作为输入,而plt.bar()返回BarContainer对象。

更新:已使用版本0.2和0.3git测试了刻度标签。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接