how can i plot the graph for csv data in matplotlib - python-3.x

can you please tell me how to plot the graph for csv data.
csv file have x,y,depth,color values i want to plot the depth and color for x and y axis,i goggled many times but i didn't find anything properly.so please guide me how to plot the graph for that values?
this is i tried :
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()
my data is given bellow

I'm assuming that you want the first two columns to be used as plot axis and columns 3 and 4 as plot data.
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')

I am assuming that you want the color and depth as text annotations.
import stuff
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
create the 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})
create the annotate column
my_df['my_text']='c= '+my_df.colour.astype(str)+','+'d= '+my_df.depth.astype(str)
plot it
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

Related

plotting time and temperature in xy plot

I want to plot a xy plot where x axis contain temperature values(first column) and y axis contain time in hr:min:sec(second column) .
8.8900 06:09:95.50
9.4500 06:09:00.56
10.5800 08.06:95.48
11.6500 09:07:73.58
56.3650 00:08:00.47
85.7823 07:01:03.23
I just want to plot a xy plot.
I tried code
import numpy as np
import matplotlib.pyplot as plt
data=np.loadtxt("inpdata.txt")
plt.plot(data[:,0],data[:,1])
plt.show()
But it does not give plot.hope experts may help.Thanks.
The simplest approach would be to use pandas.
Load the file as whitespace delimited file into pandas.DataFrame object as:
import pandas as pd
from matplotlib import pyplot as plt
df = pd.read_csv('inpdata.txt', names=['temp', 'time'], delim_whitespace=True)
Then create a line plot with time as x axis:
df.plot.line(x='time')
and show the plot
plt.show()

Can I generate a contourplot from three columns of data in python without using meshgrid?

I have three columns of data. They are too large to generate meshgrids from. So e.g. in order to generate a surface plot from the data, I use a method like so
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
x, y, z = np.loadtxt('data_file', unpack=True)
df = pd.DataFrame({'x':x, 'y':y, 'z':z})
fig = plt.figure()
ax = Axes3D(fig)
surf = ax.plot_trisurf(df.x, df.y, df.z, cmap=cm.jet, linewidth=0.05)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
Is there a similar alternative to plot_trisurf for contours?

How to add color and legend by points' label one by one in python?

I want to divide and color points,val_lab(611,3) by their labels,pred_LAB(611,)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = plt.axes(projection = '3d')
ax.set_xlabel('L')
ax.set_ylabel('A')
ax.set_zlabel('B')
for i in range(0, len(val_lab)):
ax.scatter3D(
val_lab[i,0],
val_lab[i,1],
val_lab[i,2],
s = 8,
marker='o',
c = pred_LAB
#cmap = 'rainbow'
)
#ax.legend(*points.legend_elements(), title = 'clusters')
plt.show()
The problem is it shows error,
c' argument has 611 elements, which is not acceptable for use with 'x'
with size 1, 'y' with size 1.
However, if the dataset only have ten points,it can show the figure correctly, I don't know how to solve this problem, besides, how to add legend of this figure?
In your solution you would want to replace c = pred_LAB with c = pred_LAB[i]. But you do not have to use a for loop to plot the data. You can just use the following:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# generate random input data
val_lab = np.random.randint(0,10,(611,3))
pred_LAB = np.random.uniform(0,1, (611,))
# plot data
fig = plt.figure()
ax = plt.axes(projection = '3d')
ax.set_xlabel('L')
ax.set_ylabel('A')
ax.set_zlabel('B')
# create one 3D scatter plot - no for loop
ax.scatter3D(
val_lab[:,0],
val_lab[:,1],
val_lab[:,2],
s = 8,
marker='o',
c = pred_LAB,
cmap = 'rainbow',
label='my points'
)
# add legend
plt.legend()
plt.show()

Unable to customize labels and legend in Seaborn python

import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
import matplotlib.pyplot as plt
sns.set(style="darkgrid")
df = pd.read_csv('Leap_Static_trials.csv')
Length = sns.swarmplot(x='name', y= 'length', data= df, color = 'green')
Width = sns.swarmplot(x='name', y= 'width', data= df, color = 'red')
plt.legend(labels=['Length','Width'])
plt.show()
From my dataset df I am plotting the length and width of the fingers taken from Leap Motion Controller. I am unable to change the legend to include the second color (red) which signifies the width.
Please find the attached figure as well. Your help is much appreciated. :)
Adding the parameter label= to a plot command usually creates the legend handles and labels automatically. In this case, seaborn creates handles for each column (so 5 of each). A trick is to create the legend with only the first and the last of the handles and the labels.
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
import matplotlib.pyplot as plt
sns.set(style="darkgrid")
N = 100
# df = pd.read_csv('Leap_Static_trials.csv')
names = list('abcde')
ax = plt.gca()
df = pd.DataFrame({'name': np.random.choice(names, N),
'length': np.random.normal(50, 0.7, N),
'width': np.random.normal(20, 0.5, N)})
Length = sns.swarmplot(x='name', y='length', data=df, color='green', label='Length', order=names, ax=ax)
Width = sns.swarmplot(x='name', y='width', data=df, color='red', label='Width', ax=ax)
handles, labels = ax.get_legend_handles_labels()
plt.legend([handles[0], handles[-1]], [labels[0], labels[-1]])
plt.show()

How to plot multiple line graph for a column value from a CSV file?

I tried to plot a graph for energies of 4 nodes using line graph but I'm not able to identify which line represent which node ID(1,2,3 or 4)
My csv looks something like this :
Time,Source,Destination,Bits,Energy
0,1,2,288,9.9999856
1058,1,2,288,9.9999856
1140,2,1,96,9.9999808
1958,2,3,96,9.9999952
2024,2,1,96,9.9999808
2051,2,3,288,9.999966399
3063,2,3,288,9.9999808
3126,3,2,96,9.999976
3127,2,1,288,9.9999664
3946,3,2,96,9.999961599
8340,1,2,288,9.999952
9418,1,2,288,9.999947199
9479,2,1,96,9.999942399
10299,2,3,96,9.9999712
10365,2,1,96,9.9999472
10758,2,3,288,9.999927999
11770,2,3,288,9.9999568
11832,3,2,96,9.999951999
11842,2,1,288,9.9999328
Code :
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.read_csv('DS1.csv')
for Energy,data in df.groupby('Source'):
plt.plot(data['Time'], data['Energy'])
plt.legend(data['Source'])
#print(data)
plt.xlabel('Time')
plt.ylabel('Energy')
plt.legend()
plt.show()
I actually want to plot source,energy vs Time for all sources(1 to 4)
You need to set the label.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.read_csv('DS1.csv')
for Energy, data in df.groupby('Source'):
plt.plot(data['Time'], data['Energy'], label=Energy)
#print(data)
plt.xlabel('Time')
plt.ylabel('Energy')
plt.legend()
plt.show()

Resources