我如何在matplotlib中为csv数据绘制图形

时间:2018-09-28 05:05:32

标签: python-3.x pandas matplotlib

能否请您告诉我如何绘制csv数据图。 csv文件具有x,y,depth,color值,我想绘制x和y轴的深度和颜色,我进行了多次浏览,但是找不到合适的东西。所以请指导我如何绘制该值的图形? 这是我尝试过的:

from matplotlib import pyplot as plt
from matplotlib import style
import pandas as pd
data=pd.read_csv("Tunnel.csv",names=['x','y','z','color'])
data1 =data[data.z==0]
print (data1)

# plt.plot(data[data.x],data[data.y])
plt.ylabel('yaxis')
plt.xlabel('xaxis')
plt.title('Tunnel 2d')
plt.show()

以下是我的数据 enter image description here

2 个答案:

答案 0 :(得分:0)

我假设您希望将前两列用作绘图轴,将第3列和第4列用作绘图数据。

from matplotlib import pyplot as plt
import pandas as pd

data = pd.read_csv("Tunnel.csv")

x = stats[stats.columns[2]]
y = stats[stats.columns[3]]

xlab = list(stats)[0]   #x-axis label
ylab = list(stats)[1]   #y-axis label

fig, pli = plt.subplots()
pli.show()

#Assuming it's a line graph that you want to plot
line, = pli.plot(x, y, color='g', linewidth=5, label='depth vs color')

plt.xlabel(xlab)
plt.ylabel(ylab)
plt.title(title)

fig.savefig('./Directory/Graph.png')

答案 1 :(得分:0)

我假设您希望将颜色和深度用作文本注释。

导入东西

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

创建df

dep=list(np.random.randint(0,100,10))
col=list(np.random.randint(0,100,10))
y=[int(x/3)+1 for x in range(0,10)]
x=list(range(0,10))
my_df=pd.DataFrame({'x':x,'y':y,'colour':col,'depth':dep})

创建注释列

my_df['my_text']='c= '+my_df.colour.astype(str)+','+'d= '+my_df.depth.astype(str)

绘制它

plt.figure(figsize=(20,10))
plt.plot(my_df.x,my_df.y,'o')
for i, txt in enumerate(my_df['my_text']):
    plt.annotate(txt, (x[i],y[i]), size=10, xytext=(0,0), ha='left', textcoords='offset points', bbox=dict(facecolor='none', edgecolor='red'))

plt.ylabel('yaxis')
plt.xlabel('xaxis')
plt.title('Tunnel 2d')
plt.show()

Result