Showing multiple Line Legends in Matplotlib - python

I am trying to display all 4 legends of my line graph, with the Column headers serving as the respective Legend names.
Is there an elegant way of executing this without having to write individual lines of code to plot and label each column?
Examples of my current data set are as follows:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
x = pd.Series(np.array([1,2,3,4,5,6,7,8,9,10]))
y = pd.DataFrame(np.random.rand(10,4))
y.columns = ["A","B","C","D"]
fig, ax = plt.subplots(figsize=(10, 7))
ax.plot(x, y, label=True)

Indeed you can use the plot function defined in pandas:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
x = pd.Series(np.array([1,2,3,4,5,6,7,8,9,10]))
y = pd.DataFrame(np.random.rand(10,4))
y.columns = ["A","B","C","D"]
y['x'] = x
fig, ax = plt.subplots(figsize=(10, 7))
y.plot(ax=ax)

Related

Circular contour map in python

I have a 120mm diameter circular disk, where I measure temperature at 20 different locations. These measurement locations are at random places. I am looking for a way to plot it as in attached desired plot link. When I used tricontour, It just plots the random points. I am unable to find a way to fill the circle as in below attached pic. Is there any other way to plot this? Spent lot of time searching for it with no success.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = {"x": [110,50,-85,20,45,0,-80,-30,-105,80], "y":
[0,100,75,-90,20,115,-85,-20,-45,-90],"z":[10,2,6,4,9,12,2,6,4,12]}
x = data['x']
y = data['y']
z = data['z']
f, ax = plt.subplots(1)
plot = ax.tricontourf(x,y,z, 20)
ax.plot(x,y, 'ko ')
circ1 = Circle((0, 0), 120, facecolor='None', edgecolor='r', lw=5)
ax.add_patch(circ1)
f.colorbar(plot)
Example data :
Desired plot:
What I got from tricontour:
There is much data to do a really nice coontour plot, but here is a solution with your data and an example with a substantially larger dataset:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.tri as tri
data = {"x": [110,50,-85,20,45,0,-80,-30,-105,80], "y":
[0,100,75,-90,20,115,-85,-20,-45,-90],"z":[10,2,6,4,9,12,2,6,4,12]}
df = pd.DataFrame(data)
fig = plt.figure()
ax = fig.add_subplot(projection='polar')
ax.set_title("tricontour")
ax.tricontourf(df["x"], df["y"], df["z"],20)
plt.show()
which gives
and for a larger dataframe:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df= pd.DataFrame(np.random.randint(0,1000,size=(1000, 3)), columns=list('XYZ'))
fig = plt.figure()
ax = fig.add_subplot(projection='polar')
ax.set_title("tricontour")
ax.tricontourf(df["X"], df["Y"], df["Z"],20)
plt.show()
which returns

How to draw multiple lines with Seaborn?

I am trying to draw a plot with two lines. Both with different colors. And different labels. This is what I have come up with.
This is code that I have written.
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
data1 = pd.read_csv("/content/drive/MyDrive/Summer-2020/URMC/training_x_total_data_ones.csv", header=None)
data2 = pd.read_csv("/content/drive/MyDrive/Summer-2020/URMC/training_x_total_data_zeroes.csv", header=None)
sns.lineplot(data=data1, color="red")
sns.lineplot(data=data2)
What am I doing wrong?
Edit
This is how my dataset looks like
So, I just added another color in the second line and that seemed to work.
import random
import numpy as np
import seaborn as sns
mu, sigma = 0, 0.1
s = np.random.normal(mu, sigma, 100)
mu1, sigma1 = 0.5, 1
t = np.random.normal(mu1, sigma1, 100)
sns.lineplot(data= s, color = "red")
sns.lineplot(data= t, color ="blue")
Try specifying the x and y of the call to sns.lineplot?
import pandas as pd
import numpy as np
import seaborn as sns
x = np.arange(10)
df1 = pd.DataFrame({'x':x,
'y':np.sin(x)})
df2 = pd.DataFrame({'x':x,
'y':x**2})
sns.lineplot(data=df1, x='x', y='y', color="red")
sns.lineplot(data=df2, x='x', y='y')
Without doing so, I get a similar plot as yours.

How do I update 3D quiver FuncAnimation from a data in csv file?

I need help on how to update 3D quiver head value from csv
currently, I have a csv file with 3 columns of x, y, z axis that I want to update into u,v,w variable on my python code.
The problem I am facing is that the result animation does not animate properly. It is a static picture shown below.
https://i.stack.imgur.com/Os8FX.png
I'm sure that I must have messed up on how to iterate/read the csv data file.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots(subplot_kw=dict(projection="3d"))
# Reading the data from a CSV file using pandas
repo = pd.read_csv('test.csv',sep=',',header=0)
data = np.array((repo['x'].values, repo['y'].values, repo['z'].values))
def get_arrow():
x = 0
y = 0
z = 0
u = data[0][:]
v = data[1][:]
w = data[2][:]
return x,y,z,u,v,w
quiver = ax.quiver(0,0,0,0,0,0)
ax.set_xlim(-.5, .5)
ax.set_ylim(-.5, .5)
ax.set_zlim(-.5, .5)
def update(theta):
global quiver
quiver.remove()
quiver = ax.quiver(*get_arrow())
ani = FuncAnimation(fig, update, frames=np.linspace(0,2*np.pi,200), interval=50)
plt.show()
I'm not sure how the arrows will behave because the data is unknown, but I tried to create them with sample data. I've also included a library for GIF images and jupytert, so you can modify it to suit your environment.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation
import random
from IPython.display import HTML
from matplotlib.animation import PillowWriter
random.seed(20210110)
repo = (pd.DataFrame({'x':np.random.randint(0,5, size=50),
'y':np.random.randint(0,5, size=50),
'z':np.random.randint(0,5, size=50)}))
data = np.array((repo['x'].values, repo['y'].values, repo['z'].values))
fig, ax = plt.subplots(subplot_kw=dict(projection="3d"))
quiver = ax.quiver([],[],[],[],[],[])
ax.set_xlim(-5, 5)
ax.set_ylim(-5, 5)
ax.set_zlim(-5, 5)
def update(i):
global quiver
quiver.remove()
quiver = ax.quiver(0,0,0,data[0][i],data[1][i],data[2][i])
ani = FuncAnimation(fig, update, frames=50, interval=50)
# plt.show()
ani.save('./quiver_test_ani.gif', writer='pillow')
plt.close()
# jupyter lab
# HTML(ani.to_html5_video())

Python pandas plot linechart with data points

I would like to plot a linechart based on column A. Based on Column sig I would like to add some markers to the chart A:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.DataFrame(np.random.randn(120), columns=list('A'))
data['sig'] = np.NaN
data['sig'] = np.where((data['A'] > 1), data['A'], data['sig'] )
data.plot(grid=True)
plt.show()
I tried to add markevery=data['sig'] to the plot() statement, but it gave me several errors. Any hints?
Why not plot directly in matplotlib?
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.DataFrame(np.random.randn(120), columns=list('A'))
data['sig'] = np.NaN
data['sig'] = np.where((data['A'] > 1), data['A'], data['sig'] )
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(data["A"])
ax.scatter(data.index, data["sig"])

Pandas Series Plot and GridSpec

I'm having problems with the following code:
import numpy as np
import pandas as pd
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
xx = np.arange(10)
yy = np.arange(10)
zz = pd.Series(np.arange(10))
fig = plt.figure()
gs = gridspec.GridSpec(1,6)
ax0 = plt.subplot(gs[0,0:2])
zz.plot(ax=ax0)
ax1 = plt.subplot(gs[0,2:4])
zz.plot(ax=ax1)
ax2 = plt.subplot(gs[0,4:])
#plt.plot(xx,yy)
zz.plot(ax=ax2)
plt.savefig('test.png')
plt.close()
I get the error:
IndexError: index 4 is out of bounds for axis 1 with size 4
However, when I substitute the
zz.plot(ax=ax2)
with
plt.plot(xx,yy)
it works fine. Can anyone help me understand why Pandas generates this error?

Categories

Resources