Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

python - Placing text values on axis instead of numeric values

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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). enter image description here

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

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...