[英]How to set char as labels on x axis? matplotlib
I have a set of characters eg ['a','a','b','b']
. 我有一组字符,例如
['a','a','b','b']
。 When I plot them this way: 当我以这种方式绘制它们时:
import matplotlib.pyplot as plt
x_labels = ['a','a','b','b']
y = [0,1,2,3]
plt.plot(x_labels,y)
plt.show()
This is what I get: 这是我得到的:
However, I would like to have on x-axis: a,a,b,b
, not just a,b
. 但是,我想在x轴上:
a,a,b,b
,而不仅仅是a,b
。
How can I accomplish this? 我该怎么做?
The following should work for you: 以下应该为您工作:
import matplotlib.pyplot as plt
import numpy as np
x_labels = ['a','a','b','b']
# Create dummy x values, with a value for every label entry
x = np.r_[:len(x_labels)]
y = [0,1,2,3]
plt.scatter(x, y, color='r', marker='x')
# Change the xticks as desired
plt.xticks(x, x_labels)
plt.show()
This trick is to set the x-values as placeholder integers and then change their label to whatever you desire. 该技巧是将x值设置为占位符整数,然后将其标签更改为所需的值。
This gave me the following plot, which I think is what you desired: 这给了我以下情节,我想这就是你想要的:
You can use dummy integers to set the position of the points and label the respective ticks according to your x_labels
array 您可以使用虚拟整数设置点的位置并根据
x_labels
数组标记各个刻度
import matplotlib.pyplot as plt
x_labels = ['a','a','b','b']
y = [0,1,2,3]
plt.plot(range(len(x_labels)),y)
plt.xticks(range(len(x_labels)), x_labels)
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.