matplotlib如何绘制字符串

问题描述 投票:1回答:1

当我意识到自己正在绘制字符串数据并且我的绘图未反映正在处理的数据时,我遇到了一个问题。似乎matplotlib.pyplot在传递字符串值并继续绘制某些内容时不会产生错误,但是它到底绘制了什么?它显示比例尺的数字,但它们只是字符串值的列表,与数字关系无关。它如何决定在哪里绘制点?

这是一个代码段,用于说明我的问题和下面的图表。

import matplotlib.pyplot as plt

# Define data arrays
x = range(10)
data = [4.73, 5.01, 5.29, 6.75, 4.48, 4.49, 5.44, 5.53, 4.89, 4.59]
strData = ['4.73', '5.01', '5.29', '6.75', '4.48', '4.49', '5.44', '5.53', '4.89', '4.59']

# Open figure for plotting
fig = plt.figure()

# Define axis for plotting
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()

# Plot data
lns1 = ax1.plot(x, data, '-r', label = 'Float')
# Plot string data  
lns2 = ax2.plot(x, strData, 'ob', label = 'String')

# Compile labels
lns = lns1+lns2
labs = [l.get_label() for l in lns]

# Plot the legend
fig.legend(lns, labs, loc='upper right', fontsize= 9, prop={'size':9}, numpoints=1, framealpha=1)

# Show figure
plt.show()

enter image description here

python string matplotlib plot floating-point
1个回答
0
投票
时,matplotlib.pyplot不会产生错误。

如您所见,它将按照您提供的顺序使用字符串,这意味着索引号最低的str将首先被绘制,然后索引号为1的字符串将被绘制(如您在第二个y轴上看到的那样, 4.73之后是5.01和5.29。每个值之间的距离只是一个,因为matplotlib没有排序字符串的概念。

您可以看到,如果使用范围而不是字符串列表:

strData = list(range(10))
ax2.set_yticks(strData)

它将产生相同的结果:enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.