How do I plot vertical strips in matplotlib - python-3.x

I want to show the value of a 0 or 1 array on a plot with other timeseries.
How can I achieve something like the grey lines below - except mine will oscillate a lot more.
series.
For example, how to add osc here:
import numpy as np
import matplotlib.pyplot as plt
import datetime
import pandas as pd
n = 100
x = range(n)
y = np.random.rand(100)
osc = np.random.randint(2, size=n)
plt.plot(x,y)
plt.show(block=True)

Well, you can loop through the values and call axvspan(x0,x1,color=...,alpha=...);
import numpy as np
import matplotlib.pyplot as plt
n = 100
x = range(n)
y = np.random.randn(100).cumsum()
osc = np.random.randint(2, size=n)
plt.plot(x, y, color='crimson')
for x0, x1, os in zip(x[:-1], x[1:], osc):
if os:
plt.axvspan(x0, x1, color='blue', alpha=0.2, lw=0)
plt.margins(x=0)
plt.show()
Note that only the first 99 values of osc are used, as there are only 99 intervals.

See code below:
import numpy as np
import matplotlib.pyplot as plt
n = 100
x = range(n)
y = np.random.rand(100)
osc = np.random.randint(2, size=n)
fig,ax = plt.subplots()
ax.plot(x,y)
ax.axvspan(0,5,facecolor='grey', alpha=0.4)
plt.show()
Documentation on axvspan can be found here: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.axvspan.html.
Similarly you can use axvline for just vertical lines.

Related

Scatter points assigned colour from CSV file

I am importing CSV data in the format x,y,z,p to plot a trisurface which has the scatter plots displayed on top.
The trisurface script works (ax.plot_trisurf), however, I would like to colour the scatter points (ax.scatter) according to either the 1 or -1 assigned in the fourth column of the CSV file.
enter image description here
The x,y,z data is complicated and can't be coloured, hence trying to assign it as simply as possible in the fourth column.
I have attached a basic image, essentially I just want to be able to have a selection of the red dots a different colour without affecting the trisurface they are on.
Any comments or suggestions are be very welcome!
My most recent error is:
ax.scatter(X, Y, np.log10(Z), c= (not p <= (0)({True: 'g', False: 'r'})), marker='o')
TypeError: 'int' object is not callable
enter code here
from typing import Any
import matplotlib
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sys
import csv
import bbox
import matplotlib.ticker as mticker
# Import CSV data
from numpy import ndarray
csvFileName = sys.argv[0]
csvData = []
with open('ParvaluesMESS.csv', 'r') as csvfile:
csvReader = csv.reader(csvfile, delimiter=',')
for csvRow in csvReader:
csvData.append(csvRow)
csvData = np.array(csvData)
csvData = csvData.astype(float)
X, Y, Z, p = csvData[:,0], csvData[:,1], csvData[:,2], csvData[:,3]
# Plot management: note Z is logged
# Change vmin and vmax values for colorbar range if needed
# Alpha value is transparency
# 111 means 1x1 grid, first subplot
fig = plt.figure(figsize=(5,5))
ax = fig.add_subplot(111, projection='3d')
cb = ax.plot_trisurf(X, Y, np.log10(Z), cmap='coolwarm', alpha=0.75)
#cb = ax.plot_trisurf(X, Y, np.log10(Z), cmap='coolwarm', alpha=0.75, vmin=0, vmax=1)
ax.scatter(X, Y, np.log10(Z), col==(p > 0({True: 'g', False: 'r'})), marker='o')
#ax.zaxis._set_scale('log')
def log_tick_formatter(val, pos=None):
"""Reformat log ticks for display"""
return f"$10^{{{int(val)}}}$"
# Set Z axis to log
ax.zaxis.set_major_formatter(mticker.FuncFormatter(log_tick_formatter))
# ax.zaxis.set_major_locator(mticker.MaxNLocator(integer=True))
def ticklabels(ticks):
ticks_labels = []
for i in ticks:
ticks_labels.append(f'2^{np.log2(i)}')
return ticks_labels
fig.colorbar(cb, shrink=0.5)
ax.set_title("First-year sea ice PAR")
ax.set_xlabel("Ice Thickness m")
ax.set_ylabel("Snow thickness m")
ax.set_zlabel("µmol $^{m-2}$ $^{s-1}$")
ax.view_init(azim=70, elev=30)
ax.set_xlim3d(20, 350)
image_format = 'png' # e.g .png, .svg, etc.
image_name = 'test.eps'
plt.show()
fig.savefig(image_name, format=image_format, dpi=1200)
it was resolved by rearranging into arrays:
from typing import Any
import matplotlib
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sys
import matplotlib.ticker as mticker
from numpy import ndarray
data=pd.read_csv('ParvaluesMESS.csv',header=None,sep=',',names=.
['Ice','Snow','umol','P'])
x=data[['Ice']].to_numpy()
y=data[['Snow']].to_numpy()
z=data[['umol']].to_numpy()
p=data[['P']].to_numpy()
x=(x.astype(float)).flatten()
y=(y.astype(float)).flatten()
z=(z.astype(float)).flatten()
p=(p.astype(float)).flatten()
fig = plt.figure(figsize=(5, 5))
ax = fig.add_subplot(111, projection='3d')
cb = ax.plot_trisurf(x, y, np.log10(z), cmap='coolwarm', alpha=0.75)
ax.scatter(x, y, np.log10(z),c=p,cmap='RdYlGn')
#your formats
def log_tick_formatter(val, pos=None):
"""Reformat log ticks for display"""
return f"$10^{{{int(val)}}}$"
# Set Z axis to log
ax.zaxis.set_major_formatter(mticker.FuncFormatter(log_tick_formatter))
# ax.zaxis.set_major_locator(mticker.MaxNLocator(integer=True))
def ticklabels(ticks):
ticks_labels = []
for i in ticks:
ticks_labels.append(f'2^{np.log2(i)}')
return ticks_labels
fig.colorbar(cb, shrink=0.5)
ax.set_title("First-year sea ice PAR")
ax.set_xlabel("Ice Thickness m")
ax.set_ylabel("Snow thickness m")
ax.set_zlabel("µmol $^{m-2}$ $^{s-1}$")
ax.view_init(azim=70, elev=30)
ax.set_xlim3d(20, 350)
image_name = 'BenImag'
image_format = 'png' # e.g .png, .svg, etc.
plt.show()
fig.savefig(image_name, format=image_format, dpi=1200)

No output for seaborn distplot

I was trying to plot a seaborn distplot.
sample code:
import pandas as pd
import seaborn as sns
import numpy as np
import scipy
import matplotlib.pyplot as plt
# data
np.random.seed(365)
x1 = np.random.normal(10, 3.4, size=1000) # mean of 10
df = pd.DataFrame({'x1': x1})
def map_pdf(x, **kwargs):
mu, std = scipy.stats.norm.fit(x)
x0, x1 = p1.axes[0][0].get_xlim() # axes for p1 is required to determine x_pdf
x_pdf = np.linspace(x0, x1, 100)
y_pdf = scipy.stats.norm.pdf(x_pdf, mu, std)
plt.plot(x_pdf, y_pdf, c='r')
p1 = sns.displot(data=df, x='x1', kind='hist', bins=40, stat='density')
p1.map(map_pdf, 'x1')
not sure why I am not getting any output after executing the above code!
Upon execution above code, i am getting this,
<seaborn.axisgrid.FacetGrid at 0x7f6a6fa0f820>
Any help on this will be highly appreciated.
Thank you in advance for the support!
Use the plt.show to display your plot. The same was recreated and furnished below with the solution.
import pandas as pd
import seaborn as sns
import numpy as np
import scipy
import matplotlib.pyplot as plt
# data
np.random.seed(365)
x1 = np.random.normal(10, 3.4, size=1000) # mean of 10
df = pd.DataFrame({'x1': x1})
def map_pdf(x, **kwargs):
mu, std = scipy.stats.norm.fit(x)
x0, x1 = p1.axes[0][0].get_xlim() # axes for p1 is required to determine x_pdf
x_pdf = np.linspace(x0, x1, 100)
y_pdf = scipy.stats.norm.pdf(x_pdf, mu, std)
plt.plot(x_pdf, y_pdf, c='r')
p1 = sns.displot(data=df, x='x1', kind='hist', bins=40, stat='density')
p1.map(map_pdf, 'x1')
plt.show(p1)

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()

How to rotate matplotlib.patches.Polygon?

How to rotate matplotlib.patches.Polygon? The output from the code below shows nothing.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib as mpl
fig, ax = plt.subplots(figsize=(10,3))
x = [0.3,0.6,.5,.4]
y = [0.7,0.7,0.9,0.9]
trapezoid = patches.Polygon(xy=list(zip(x,y)), fill=False)
t_start = ax.transData
t = mpl.transforms.Affine2D().rotate_deg(-45)
t_end = t_start + t
trapezoid.set_transform(t_end)
print(repr(t_start))
print(repr(t_end))
ax.add_patch(trapezoid)
plt.show()
When composing the tranformations, you must use t_end = t + t_start instead of t_start + t. The + operator is overloaded: a + b means to first apply a and then apply b. For affine transformations this means the matrix product B#A where A and B are the transformation matrices of a and b respectively. The matrix product is not commutative.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib as mpl
import copy
fig, ax = plt.subplots(figsize=(10,3))
x = [0.3,0.6,.5,.4]
y = [0.7,0.7,0.9,0.9]
trapezoid = patches.Polygon(xy=list(zip(x,y)), fill=False)
ax.add_patch(copy.copy(trapezoid))
t_start = ax.transData
t = mpl.transforms.Affine2D().rotate_deg(-45)
t_end = t + t_start
trapezoid.set_transform(t_end)
ax.add_patch(trapezoid)
plt.show()

Getting rid of extra lines in Python shapefile plot?

I am trying to do a basic plot of the world map using Python and the Matplotlib library. However, when I plot the polygons the plot shows many straight lines that do not seem to be part of the polygon. I am relatively new at working with shapefiles but the code I'm using has worked for a previous shapefile I used, so I'm confused and wondering what might be missing in the code.
The code I'm using is:
import numpy as np
import pandas as pd
import shapefile as shp
import matplotlib.pyplot as plt
import seaborn as sns
import os
sns.set(style='whitegrid', palette='ocean', color_codes=True)
sns.mpl.rc('figure', figsize=(10,6))
sf = shp.Reader(shp_path)
def plot_map(sf, x_lim = None, y_lim = None, figsize = (11,9)):
'''
Plot map with lim coordinates
'''
plt.figure(figsize = figsize)
id=0
for shape in sf.shapeRecords():
x = [i[0] for i in shape.shape.points[:]]
y = [i[1] for i in shape.shape.points[:]]
plt.plot(x, y, 'k')
if (x_lim == None) & (y_lim == None):
x0 = np.mean(x)
y0 = np.mean(y)
plt.text(x0, y0, id, fontsize=10)
id = id+1
if (x_lim != None) & (y_lim != None):
plt.xlim(x_lim)
plt.ylim(y_lim)
plot_map(sf)
plt.show()
The following link shows resulting graph (I'm not allowed to post pictures yet?):
Any help is appreciated, thank you all!
pls use 'k.', or use scatter instead of plot
import numpy as np
import pandas as pd
import shapefile as shp
import matplotlib.pyplot as plt
import seaborn as sns
import os
sns.set(style='whitegrid', palette='ocean', color_codes=True)
sns.mpl.rc('figure', figsize=(10,6))
sf = shp.Reader(shp_path)
def plot_map(sf, x_lim = None, y_lim = None, figsize = (11,9)):
'''
Plot map with lim coordinates
'''
plt.figure(figsize = figsize)
id=0
for shape in sf.shapeRecords():
x = [i[0] for i in shape.shape.points[:]]
y = [i[1] for i in shape.shape.points[:]]
## change here
plt.plot(x, y, 'k.')
if (x_lim == None) & (y_lim == None):
x0 = np.mean(x)
y0 = np.mean(y)
plt.text(x0, y0, id, fontsize=10)
id = id+1
if (x_lim != None) & (y_lim != None):
plt.xlim(x_lim)
plt.ylim(y_lim)
plot_map(sf)
plt.show()

Resources