使用matplotlib做散点图

时间:2017-04-04 17:50:34

标签: python matplotlib plot scatter

当我尝试使用matplotlib绘制代码时,我看到一个没有绘图的空图。我附上代码和空白图。请告诉我我错过了什么。谢谢!

empty window with no plot

from datetime import datetime
start_time = datetime.now()
print(start_time)

import pandas as pd
import numpy as np

file1 = 'fn_data.csv'
import matplotlib.pyplot as plt
#import pylab

# Read the .txt file into a dataframe
data = pd.read_csv(file1, encoding = "ISO-8859-1", header=0, delimiter=',')
rating=data.iloc[:,0]
chef=data.iloc[:,3]
print(rating)

mydict={}
i = 0
for item in chef:
    if(i>0 and item in mydict):
        continue
    else:
       i = i+1
       mydict[item] = i

chef_codes=[]
for item in chef:
    chef_codes.append(mydict[item])

print(chef_codes)
chef_codes_new=np.array(chef_codes)
rating_new=np.array(rating)
print(type(chef_codes_new),type(rating_new))
print(np.max(chef_codes_new),np.max(rating_new))
plt.plot(kind='scatter',x=chef_codes_new,y=rating_new, marker='o', ms = 10, alpha=1, color='b')
plt.axis([0, 1000, 0, 5])
plt.show()
plt.savefig("fig1.png")


end_time = datetime.now()
print(end_time)

2 个答案:

答案 0 :(得分:0)

def scatterPlot(X,Y):
    ids= ['green' if y == 0 else 'red' for y in Y]
    plt.scatter(X[:,0], X[:,1], color=ids)
    plt.title("Scatter Plot")
    return

scatterPlot(x,y)

它只是scatter plot的一个例子,希望它可以帮助你解决问题。

答案 1 :(得分:0)

如果plt.scatter有效,plt.plot也会有效。问题是您已将pandas.DataFrame.plot的语法与pyplot.plot的命令混合在一起。

所以,而不是

plt.plot(kind='scatter',x=chef_codes_new,y=rating_new, marker='o', ms = 10, alpha=1, color='b')

你需要

plt.plot(chef_codes_new,rating_new, marker='o', ms = 10, alpha=1, color='b')

语法为plt.plot(x,y, *args, **kwargs),您无法在pyplot图中使用kind="scatter"。如果需要散点图,请使用plt.scatter