在轴上放置文本值,而不是数字值 [英] Placing text values on axis instead of numeric values

查看:101
本文介绍了在轴上放置文本值,而不是数字值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python 3.2中创建了一个简单的单词频率计算器.现在,我想创建一个图以可视化结果. x轴将包含频率结果,我想将最常用的单词添加到y轴.如何在pylab轴上添加文本而不是数字?预先感谢!

I've created a simple word frequency calculator in python 3.2. Now I want to create a plot to visualize the results. The x-axis would contain frequency results and I want to add the most frequent words to the y-axis. How can I add text instead of numbers to a pylab axis? Thanks in advance!

推荐答案

我要假设,因为您要在 您想要水平条形图的x轴而不是y轴.

I am going to assume, that because you want to display the frequencies on x-axis instead of the y-axis, that you want a horizontal bar-plot.

调整标签以在x轴上打印仅需要您进行以下操作: 使用xticks命令:

Adjusting the labels to print on the x-axis instead simply requires you to use the xticks command:

import matplotlib.pyplot as plt
import numpy as np
x_values = [0.1, 0.3, 0.4, 0.2]
y_values = ["word 1", "word 2", "word 3", "word 4"]
y_axis = np.arange(1, 5, 1)

plt.barh(y_axis, x_values, align='center')
plt.yticks(y_axis, y_values)
plt.show()

这将产生以下图表(但是可能有更好的方法 不需要您摆弄显示y标签的位置).

This will result in the following chart (but there probably is a better way that will not require you to fiddle with spacing where to display you y-labels).

实际上要多考虑一下-我认为类似以下内容更符合您的想法(我想我应该现在停止,因为它不可避免地表明我对使用matplotlib感到无聊,没有经验):

Actually thinking a bit more about it - I think something like the following is more what you had in mind (I think I should stop now, as it inevitably shows that I am laughably inexperienced using matplotlib):

import matplotlib.pyplot as plt
import numpy as np
y_values = [0.1, 0.3, 0.4, 0.2]
text_values = ["word 1", "word 2", "word 3", "word 4"]
x_values = np.arange(1, len(text_values) + 1, 1)

plt.bar(x_values, y_values, align='center')
# Decide which ticks to replace.
new_ticks = ["word for " + str(y) if y != 0.3 else str(y) for y in y_values]
plt.yticks(y_values, new_ticks)
plt.xticks(x_values, text_values)
plt.show()

这篇关于在轴上放置文本值,而不是数字值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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