绘制一个图,其中 Y 轴文本数据(非数字)和 X 轴数字数据

2024-01-16

我可以根据“简单”字典在 matplotlib 中创建一个简单的柱状图:

import matplotlib.pyplot as plt
D = {u'Label1':26, u'Label2': 17, u'Label3':30}
plt.bar(range(len(D)), D.values(), align='center')
plt.xticks(range(len(D)), D.keys())
plt.show()

enter image description here But, how do I create curved line on the text and numeric data of this dictionarie, I do not know?

Т_OLD = {'10': 'need1', '11': 'need2', '12': 'need1', '13': 'need2', '14': 'need1'}

Like the picture below enter image description here


您可以使用 numpy 将字典转换为具有两列的数组,并且可以绘制该数组。

import matplotlib.pyplot as plt
import numpy as np

T_OLD = {'10' : 'need1', '11':'need2', '12':'need1', '13':'need2','14':'need1'}
x = list(zip(*T_OLD.items()))
# sort array, since dictionary is unsorted
x = np.array(x)[:,np.argsort(x[0])].T
# let second column be "True" if "need2", else be "False
x[:,1] = (x[:,1] == "need2").astype(int)

# plot the two columns of the array
plt.plot(x[:,0], x[:,1])
#set the labels accordinly
plt.gca().set_yticks([0,1])
plt.gca().set_yticklabels(['need1', 'need2'])

plt.show()

以下是一个版本,与词典的实际内容无关;唯一的假设是键可以转换为浮点数。

import matplotlib.pyplot as plt
import numpy as np

T_OLD = {'10': 'run', '11': 'tea', '12': 'mathematics', '13': 'run', '14' :'chemistry'}
x = np.array(list(zip(*T_OLD.items())))
u, ind = np.unique(x[1,:], return_inverse=True)
x[1,:] = ind
x = x.astype(float)[:,np.argsort(x[0])].T

# plot the two columns of the array
plt.plot(x[:,0], x[:,1])
#set the labels accordinly
plt.gca().set_yticks(range(len(u)))
plt.gca().set_yticklabels(u)

plt.show()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

绘制一个图,其中 Y 轴文本数据(非数字)和 X 轴数字数据 的相关文章

随机推荐