我试图通过创建一个数组来硬编码绘图的主要刻度,然后将其附加到图形的x轴上。然而,我不能让数组正确地出来。我创建了一个空列表xticks,我想每第5个值更新一次major_ticks中的正确值,但更新后的值只是major_ticks中值的前几个字符
{
length_x = 21
import numpy as np
xticks=np.full(length_x,'',dtype=str)
#print(xticks) returns ['' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '']
major_ticks=np.linspace(-10,10,5,dtype=int)
#print(major_ticks) returns [-10 -5 0 5 10]
i=0
for j in range(len(xticks)):
if j%5==0:
xticks[j]=str(major_ticks[i])
i+=1
print(xticks) #returns ['-' '' '' '' '' '-' '' '' '' '' '0' '' '' '' '' '5' '' '' '' '' '1']
}请告诉我为什么会这样,我已经用头撞墙三个小时了。
发布于 2019-07-22 07:16:14
这是因为np.full最初生成的不是字符串数组,而是字符数组:
np.full(length_x,'',dtype=str).dtype
dtype('<U1')通常,我不建议对字符串操作使用numpy。用xticks = [''] * length_x替换xticks=np.full(length_x,'',dtype=str)会给你想要的东西。
发布于 2019-07-22 07:17:54
我认为您的np.full声明中有一些奇怪的地方。切换到使用python列表将使其更容易:
major_ticks=np.linspace(-10,10,5,dtype=int)
xticks = []
i=0
for j in range(length_x):
if j%5==0:
tick = str(major_ticks[i])
i += 1
else:
tick = ''
xticks.append(tick)
print(xticks)发布于 2019-07-22 07:57:00
In [129]: major_ticks=np.linspace(-10,10,5,dtype=int)
In [130]: major_ticks.shape
Out[130]: (5,)
In [133]: major_ticks
Out[133]: array([-10, -5, 0, 5, 10])
In [134]: major_ticks.astype(str)
Out[134]: array(['-10', '-5', '0', '5', '10'], dtype='<U21')从major_ticks生成字符串。21比所需的要大,但是谁在计算呢?
In [135]: xticks=np.full(21,'',dtype='U21')
In [136]: xticks
Out[136]:
array(['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', ''], dtype='<U21')
In [138]: i=0
...: for j in range(len(xticks)):
...: if j%5==0:
...: xticks[j] = str(major_ticks[i])
...: i+=1
...:
...:
In [139]: xticks
Out[139]:
array(['-10', '', '', '', '', '-5', '', '', '', '', '0', '', '', '', '',
'5', '', '', '', '', '10'], dtype='<U21')但是我们可以直接填充字符串数组:
In [140]: xticks=np.full(21,'',dtype='U21')
In [141]: xticks[0::5] = major_ticks
In [142]: xticks
Out[142]:
array(['-10', '', '', '', '', '-5', '', '', '', '', '0', '', '', '', '',
'5', '', '', '', '', '10'], dtype='<U21')将整数添加到xticks时,会将其转换为字符串dtype。
https://stackoverflow.com/questions/57137604
复制相似问题