绘制一个图,其中Y轴文本数据(非数字)和X轴数字数据 [英] Draw a plot in which the Y-axis text data (not numeric), and X-axis numeric data

查看:71
本文介绍了绘制一个图,其中Y轴文本数据(非数字)和X轴数字数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can create a simple columnar diagram in a matplotlib according to the 'simple' dictionary:

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()

但是,我不知道如何在此字典的文本和数字数据上创建曲线?

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'}

就像下面的图片

推荐答案

您可以使用numpy将字典转换为具有两列的数组,并可以对其进行绘制.

You may use numpy to convert the dictionary to an array with two columns, which can be plotted.

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()

以下将是一个版本,它独立于词典的实际内容;唯一的假设是键可以转换为浮点数.

The following would be a version, which is independent on the actual content of the dictionary; only assumption is that the keys can be converted to floats.

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()

这篇关于绘制一个图,其中Y轴文本数据(非数字)和X轴数字数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆