matplotlib将real转换为分类

时间:2017-03-17 01:07:40

标签: python matplotlib data-visualization

如果我有一组数据

python x_data = array([-0.5597064565292805, -0.6044992007582148, 0.22877491676881043, -1.2332817779977419, 0.42077626119484773, 1.825509016838052, 0.3476645527864688, -0.35439666443655543, 0.8783711637081933, -0.438777582274935], dtype=object)

我无法使用matplotlib绘制带有x作为分类值的条形图。无论我做什么,它都会迫使转换成真实的。任何想法如何使每个数字成为一个分类?

1 个答案:

答案 0 :(得分:0)

您可以将y数据绘制为数字0,1,2,3等的函数,然后将ticklabels设置为x_data中的字符串。

enter image description here

import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt

x_data = [-0.5597064565292805, -0.6044992007582148, 0.22877491676881043,
       -1.2332817779977419, 0.42077626119484773, 1.825509016838052,
       0.3476645527864688, -0.35439666443655543, 0.8783711637081933,
       -0.438777582274935]

y_data = np.random.rand(len(x_data))

x_strings=["{:.3f}".format(x) for x in x_data]

plt.figure(figsize=(5,5), dpi=64./5)
plt.bar(range(len(x_data)), y_data )
plt.xticks(range(len(x_data)), x_strings)

plt.savefig(__file__+".png", dpi="figure")
plt.show()

64x64像素图像的结果看起来像

enter image description here

没有任何东西是可读的。所以它可能没有多大意义。