我试图使用matplotlib显示一些点,虽然我可以使用print命令显示它们,但matplotlib给出错误。有效的命令也在那里(注释)。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
data = np.array([[-1,-1,'C1'],[-2,-1,'C1'],[-3,-2,'C1'],[1,1,'C2'],[2,1,'C2'],[3,2,'C2']])
query=[-2.5,-1.5]
df=pd.DataFrame(data)
df.columns =['x','y','Cat']
df
for i in range(6):
if(df.ix[i]['Cat'] == 'C1'):
plt.scatter(df.iloc[i]['x'], df.iloc[i]['y'], s=150, c='r') #error line
#working linke below
#print(df.iloc[i]['x'],df.iloc[i]['y'])
else:
plt.scatter(df.iloc[i]['x'], df.iloc[i]['y'], s=150, c='b')
#working line below
#print(df.iloc[i]['x'],df.iloc[i]['y'])
请帮忙。提前致谢
感谢@Haleemur Ali的帮助我现在可以运行但仍然没有完全正常运行。并非所有要点都显示不确定原因?
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
data = np.array([[-1,-1,'r'],[-2,-1,'r'],[-3,-2,'r'],[1,1,'b'],[2,1,'b'],[3,2,'b'],[-2.5,-1.5,'y']])
query=[-2.5,-1.5]
df=pd.DataFrame(data)
df.columns =['x','y','Cat']
print(df)
plt.scatter(df.x, df.y, s=150, c=df.Cat)
图表生成
如果数字是字符串,则它们不会被识别为数字,因此它们被绘制为类别,正如您在绘制["apple", "banana", "cherry"]
时所期望的那样。您需要将数据转换为浮点数:
df[['x', 'y']] = df[['x', 'y']].astype(float)
完整代码:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = np.array([[-1,-1,'r'],[-2,-1,'r'],[-3,-2,'r'],[1,1,'b'],
[2,1,'b'],[3,2,'b'],[-2.5,-1.5,'y']])
df=pd.DataFrame(data, columns=['x','y','Cat'])
df[['x', 'y']] = df[['x', 'y']].astype(float)
plt.scatter(df.x, df.y, s=150, c=df.Cat)
plt.show()