在matplotlib中绘制字符串值

use*_*582 9 python matplotlib

我正在使用matplotlib作为图形应用程序.我正在尝试创建一个字符串作为X值的图表.但是,using plot函数需要X的数值.

如何使用字符串X值?

小智 10

你应该尝试xticks

import pylab

names = ['anne','barbara','cathy']
counts = [3230,2002,5456]

pylab.figure(1)
x = range(3)
pylab.xticks(x, names)
pylab.plot(x,counts,"g")

pylab.show()
Run Code Online (Sandbox Code Playgroud)


Imp*_*est 10

从matplotlib 2.1开始,您可以在绘图函数中使用字符串.

import matplotlib.pyplot as plt
x = ["Apple", "Banana", "Cherry"]
y = [5,2,3]

plt.plot(x, y)

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

请注意,为了保留绘图上输入字符串的顺序,您需要使用matplotlib> = 2.2.

  • 这是低估的,但我赞成它,因为它是迄今为止最紧凑的解决方案,并且在大多数情况下,不会破坏其他任何东西. (2认同)

dou*_*oug 1

这是我知道的一种可行的方法,尽管我认为创建自定义符号是实现此目的的更自然的方法。

from matplotlib import pyplot as PLT

# make up some data for this example
t = range(8)
s = 7 * t + 5
# make up some data labels which we want to appear in place of the symbols
x = 8 * "dp".split()
y = map(str, range(8))
data_labels = [ i+j for i, j in zip(x, y)]
fig = PLT.figure()
ax1 = fig.add_subplot(111)
ax1.plot(t, s, "o", mfc="#FFFFFF")     # set the symbol color so they are invisible
for a, b, c in zip(t, s, data_labels) :
    ax1.text(a, b, c, color="green")

PLT.show()
Run Code Online (Sandbox Code Playgroud)

因此,这将“dp1”,“dp2”,...代替每个原始数据符号 - 实质上创建自定义“文本符号”,尽管我再次相信有一种更直接的方法可以在 matplotlib 中做到这一点(不使用艺术家)。