Skip to content

Instantly share code, notes, and snippets.

@prerakmody
Last active August 10, 2021 13:45
Show Gist options
  • Save prerakmody/1e12086ca0efe57793870e7cc86a5cf8 to your computer and use it in GitHub Desktop.
Save prerakmody/1e12086ca0efe57793870e7cc86a5cf8 to your computer and use it in GitHub Desktop.
Matplotlib Techniques
import matplotlib.pyplot as plt
plt.xlim([-1,20])
plt.ylim([-1,20])
plt.arrow(0, 0, 10, 10,head_width=0.5, head_length=0.5)
plt.arrow(10,10, 8,4,head_width=0.5, head_length=0.5)
import matplotlib.pyplot as plt
if __name__ == "__main__":
errors = [0.338, 0.325, 0.305, 0.272, 0.267]
plt.bar(range(len(errors)), errors)
plt.xticks(range(len(errors)), ["5", "10", "30", "50",'100'])
plt.xlabel('Iterations (T)')
plt.ylabel('Test Error')
plt.ylim([0,0.6])
plt.xticks(rotation=90)
for i, error in enumerate(errors):
plt.text(i-0.25, error+0.01 , str(error), color='blue', fontweight='bold')
import os
import cv2
import copy
import pprint
import numpy as np
from shapely.geometry import Polygon
from descartes import PolygonPatch
import matplotlib.pyplot as plt
%matplotlib inline
def find_contours(img_url_local, class_id_study=0, only_classes=0,verbose=0, show_image=0):
if os.path.exists(img_url_local):
img = cv2.imread(img_url_local, cv2.IMREAD_UNCHANGED)
h, w = len(img), len(img[0])
img_class_ids, counts = np.unique(img, return_counts=True)
if verbose or only_classes:
pprint.pprint(dict(zip(img_class_ids, counts)))
if only_classes:
return [], [], [], h, w
for class_id in img_class_ids:
if class_id not in [class_id_study]:
continue
if verbose:
print (' - class_id : ', class_id)
img_tmp = copy.deepcopy(img)
img_tmp[img_tmp != class_id] = 0
img_tmp[img_tmp == class_id] = 255
if verbose:
print (np.unique(img_tmp, return_counts=True))
if show_image:
plt.imshow(img_tmp, cmap='gray')
im2, contours, hierarchy = cv2.findContours(img_tmp, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
return im2, contours, hierarchy, h, w
else:
print (' Check image URL : ', img_url_local)
return []
def get_contour_pts(contours, hierarchy, verbose=0):
polygons_pts = []
for contour_id, contour_topology in enumerate(hierarchy[0]):
if verbose:
print (' - hierarchy : ', contour_topology)
next_contour = contour_topology[0]
prev_contour = contour_topology[1]
child_contour = contour_topology[2]
parent_countour = contour_topology[3]
if child_contour == -1 and parent_countour == -1:
polygon_pts = np.array([pts[0] for pts in contours[contour_id]])
polygons_pts.append(polygon_pts)
else:
print (' - Special case noticed! Please handle.')
return polygons_pts
def draw_scatter(polygons_pts, h, w):
f, axarr= plt.subplots(1, figsize=(10,10))
axarr.set_xlim(0, w)
axarr.set_ylim(h, 0)
for polygon_pts in polygons_pts:
plt.scatter(polygon_pts[:,0], polygon_pts[:,1])
def draw_polygon(polygons_pts, h, w, title='', save=False):
fig, ax = plt.subplots(1, figsize=(10,10))
ax.set_xlim(0, w)
ax.set_ylim(h, 0)
for polygon_pts in polygons_pts:
print (polygon_pts.shape)
if len(polygon_pts) > 2:
poly = Polygon(polygon_pts)
patch = PolygonPatch(poly, facecolor=[0,0,0.5], edgecolor=[1,1,1], alpha=0.8)
ax.add_patch(patch)
plt.title(title)
plt.tight_layout()
if __name__ == "__main__":
## PARAMS
img_url_local = '../data/cityscapes/stuttgart_000189_000019_gtFine_labelIds.png'
## STEPS
_, contours, hierarchy, h, w = find_contours(img_url_local, class_id_study=4, only_classes=0
, verbose=0, show_image=0)
if len(contours):
polygons_pts = get_contour_pts(contours, hierarchy, verbose=0)
# draw_scatter(polygons_pts, h, w)
draw_polygon(polygons_pts, h, w)
import matplotlib.pyplot as plt
def getStats(X):
x = np.arange(len(X))
y = np.mean(X, axis=1)
yerr = np.std(X, axis=1)
return x,y,yerr
def plot1(X):
x, y, yerr = getStats(X)
plt.errorbar(x, y, yerr, label='', marker='s')
plt.legend(loc = 'upper right') # plt.legend(fancybox=True, shadow=True, fontsize=8)
plt.xticks([])
plt.ylim([-0.5, 0.5])
plt.xaxis.set_tick_params(labelsize=20)
plt.grid(True)
plt.title('Title', fontsize=10);
# plt.xscale('log', basex=2)
if __name__ == "__main__":
X = [[], [], ... , [],
plot1(X)
"""
To save images to embed in latex
"""
import os
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams['figure.dpi']= 100 # keep this low, else it takes times to render on matplotlib
mpl.rc("savefig", dpi=300) # keep this high.
inline_rc = dict(mpl.rcParams) # for resetting purposes
%matplotlib inline
def plot(data): # data is a numpy array
f, axarr = plt.subplots(1, figsize=(10,10))
plt.plot(data[:,0], data[:,1], color='blue', label='MyData', linestyle=':', alpha=1.0, marker='o') # linestyle = ['-', '--', ':']
# Styling
# mpl.rcParams.update(mpl.rcParamsDefault) # set this since every run needs this
mpl.rcParams.update(inline_rc) # set this since every run needs this
plt.rc('legend', fontsize=20)
plt.rc('xtick', labelsize=15)
plt.rc('ytick', labelsize=15)
# axarr.xaxis.set_major_locator(plt.MaxNLocator(5)) # to limit the number of ticks
axarr.xaxis.get_label().set_fontsize(20)
axarr.yaxis.get_label().set_fontsize(20)
plt.xlabel('X Axis')
plt.ylabel('Y axis')
plt.title('My Plot', fontsize=30)
plt.legend(loc='upper left')
if not os.path.isdir('./images/'):
os.mkdir('images')
filename = 'images/image_' + str(datetime.datetime.now().replace(microsecond=0)) + '.png'
f.savefig(filename, bbox_inches = 'tight',pad_inches = 0, format='png')
import seaborn as sns
def heatmap(data):
sns.heatmap(tmp, annot=True, fmt='g')mp =
if __name__ == "__main__":
data = [[214051, 9114],[135, 210]]
heatmap(data)
import matplotlib.pyplot as plt
def plot(data):
f, axarr = plt.subplots(2,1, sharex=True)
axarr[0].bar(range(len(data)), data)
axarr[0].set_title('Data1')
axarr[0].set_xticks(range(len(data)))
axarr[0].set_xticklabels(['Exact','0.1','0.33','0.5','1','3','5','10','100'])
axarr[0].bar(range(len(data)), data)
axarr[0].set_title('Data2')
import matplotlib.pyplot as plt
%matplotlib inline
def plot():
# Keep a length of 12
x_0 = [1.0, 1.2, 1.3, 2.5, 3.0, 3.1] # len=6
x_1 = [3.1, 2.9, 2.0, 1.0, 1.1, 1.1, 1.0, 1.2, 1.3, 3.0, 3.5, 3.5] #len=18
x_2 = [3.4, 3.0, 2.0, 1.1, 1.1, 1.2, 1.1, 1.4, 1.2, 4.0, 4.5, 5.0] #len=30
x_3 = [5.1, 4.5, 4.0, 1.9, 1.1, 1.2, 1.3, 1.0, 1.5, 5.5, 6.7, 7.0] #len=42
x_4 = [7.1, 6.2, 5.9, 2.9, 2.0, 1.4, 1.3, 1.2, 1.3, 4.0, 4.5, 4.6] #len=54
x_5 = [4.5, 4.5, 4.4, 3.0, 2.1, 1.1, 1.2, 1.3, 1.3, 4.4, 5.0, 5.1] #len=66
x_6 = [5.1, 4.9, 4.8, 2.1, 1.3, 1.4, 1.2, 1.1, 1.2, 5.0, 5.2, 5.3] #len=78
x_plot = x_0 + x_1 + x_2 + x_3 + x_4 + x_5 + x_6
x_0_ = [1.1, 1.1, 1.4, 2.4, 3.1, 3.2]
x_1_ = [3.2, 2.7, 1.9, 1.1, 1.2, 1.1, 1.0, 1.1, 1.4, 3.1, 3.5, 3.2]
x_2_ = [3.1, 3.2, 2.5, 1.3, 1.1, 1.2, 1.1, 1.5, 1.2, 4.1, 4.6, 5.2]
x_3_ = [5.0, 4.6, 4.0, 2.2, 1.5, 1.2, 1.4, 1.0, 1.9, 6.0, 6.7, 6.9]
x_4_ = [6.5, 6.1, 6.0]
x_5_ = []
x_6_ = []
x_plot_ = x_0_ + x_1_ + x_2_ + x_3_ + x_4_ + x_5_ + x_6_
f, axarr = plt.subplots(1, figsize=(10,10))
axarr.plot(x_plot, linestyle='--', label='Prediction')
axarr.plot(x_plot_, label='Actual')
axarr.set_ylabel('Average Bird Density (birds/km2)', fontsize=15)
axarr.set_xlabel('Time', fontsize=15)
axarr.set_xticks([])
axarr.set_xticks([5,17,29,41,53,65,77])
axarr.set_xticklabels(["13/05", "14/05", "15/05", "16/05",'17/05', '18/05', '19/05'])
axarr.set_yticks([1,2,3,4,5,6,7])
axarr.set_yticklabels(['0','30','60','90', '120', '150', '180', '210'])
axarr.legend(fontsize=11)
vspan_c = 'b'
axarr.axvspan(3, 8, facecolor=vspan_c, alpha=0.1)
axarr.axvspan(15, 20, facecolor=vspan_c, alpha=0.1)
axarr.axvspan(27, 32, facecolor=vspan_c, alpha=0.1)
axarr.axvspan(39, 44, facecolor=vspan_c, alpha=0.1)
axarr.axvspan(51, 56, facecolor=vspan_c, alpha=0.1)
axarr.axvspan(63, 68, facecolor=vspan_c, alpha=0.1)
axarr.axvspan(75, 80, facecolor=vspan_c, alpha=0.1)
plt.text(65.8, 6.5, 'Note : The stripes \nrepresent night', color='blue', fontweight='bold', bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
if __name__ == "__main__":
plot()
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
x = [[], [], ..., []]
y = [[], [], ..., []]
label = [[], [], ..., []]
data = pd.DataFrame({'x': x, 'y':y, 'CE': sns_label_ce, 'DICE': sns_label_dice, 'HD95': sns_label_hd95})
palette = {'label1': ['r','g','b'], ...}
sns.set(style="darkgrid")
plt.figure(figsize=(10,5), dpi=200)
bplt = sns.boxplot(x='x', y='y', hue='label', palette=palette, data=data)
bplt.set_xlabel('',fontsize=15)
bplt.set_ylabel('',fontsize=15)
bplt.set_xticklabels(bplt.get_xticklabels(),size = 15)
bplt.set_ylim([0.0, 0.9])
# plt.setp(bplt.get_legend().get_texts(), fontsize='15')
handles, labels = bplt.get_legend_handles_labels()
bplt.legend(handles=handles[1:], labels=labels[1:],fontsize=15)
plt.savefig('plot.png', bbox_inches='tight')
from shapely import geometry
from descartes import PolygonPatch
import matplotlib.pyplot as plt
def random():
f, axarr = plt.subplots(1)
axarr.imshow(img_array)
poly = geometry.Polygon(contour_pts)
patch = PolygonPatch(poly, facecolor = [0,1,0], edgecolor = [0,1,0], alpha = 0.35)
axarr.add_patch(patch)
frame1 = plt.gca()
frame1.axes.get_xaxis().set_visible(False)
frame1.axes.get_yaxis().set_visible(False)
frame1.set_xlim(0,w)
frame1.set_ylim(0,h)
plt.savefig(img_name, bbox_inches = 'tight', pad_inches = 0, dpi = 100)
def draw_polygon(points, title='', save=False):
pt_max_x = np.max(points[:,0])
pt_max_y = np.max(points[:,1])
poly = Polygon(pts)
patch = PolygonPatch(poly, facecolor=[0,0,0.5], edgecolor=[1,1,1], alpha=0.8)
fig, ax = plt.subplots(1, figsize=(10,10))
ax.set_xlim(0, pt_max_x)
ax.set_ylim(0, pt_max_y)
ax.add_patch(patch)
plt.title(title)
plt.tight_layout()
if save:
plt.savefig('img_name', bbox_inches = 'tight', pad_inches = 0, dpi = 100)
if __name__ == "__main__":
pts = np.array([[0,0],[1,1],[0,1]])
pts = np.array([[1136, 844],[1104, 913],[1550, 969], [1104, 873]])
draw_polygon(pts)
from IPython import display
import matplotlib.pyplot as plt
f, axarr = plt.subplots(1)
w,h = 20, 20
frame1 = plt.gca()
frame1.set_xlim(0,w)
frame1.set_ylim(0,h)
cmap = plt.cm.rainbow
color_me = np.random.rand(w)
for i in range(w):
axarr.scatter(i,i, c = cmap(color_me[i]))
display.display(plt.gcf())
display.clear_output(wait=True)
plt.pause(0.2)
import matplotlib
import matplotlib.pyplot as plt
from IPython import display # [for Jupyter]
def plot_data(fig,axarr,data, IS_IPYTHON):
axarr.cla() # clear axis
axarr.set_title('Training...')
axarr.set_xlabel('X-axis')
axarr.set_ylabel('Y-axis')
axarr.plot(data)
if IS_IPYTHON:
display.display(fig) # display the figure once again
display.clear_output(wait=True) # [for jupyter] wait to clear output of the current running cell when new output is received
plt.pause(0.1) # just for lulz
if __name__ == "__main__":
IS_IPYTHON = 'inline' in matplotlib.get_backend()
print (' - IS_IPYTHON : ', IS_IPYTHON)
data = []
f,axarr = plt.subplots(1)
for i in range(10):
data.append(i+1)
plot_data(f, axarr, data, IS_IPYTHON)
if IS_IPYTHON:
display.display(f) # [for jupyter] to keep the plot from disappearing in the end
else:
plt.show() # [for scripts] to keep the plot from disappearing in the end
print ('Complete')
import random
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from sklearn.manifold import TSNE
def plot_SNE(X,Y):
X_embedded = TSNE(n_components=2).fit_transform(X)
number_of_colors = len(np.unique(Y))
color_palette = np.array(["#"+''.join([random.choice('0123456789ABCDEF') for j in range(6)]) for i in range(number_of_colors)])
colors = list(color_palette[Y])
# Also try this -- https://sashat.me/2017/01/11/list-of-20-simple-distinct-colors/
f, axarr = plt.subplots(1, figsize=(15,15))
axarr.scatter(X_embedded[:,0], X_embedded[:,1], color=colors)
axarr.set_title('t-SNE Embedding', fontsize=20)
legend_elements = []
for i in range(len(color_palette)):
legend_elements.append(
Line2D([0], [0], marker='o', color=colors[-1], label=str(i+1),
markerfacecolor=color_palette[i], markersize=20)
)
plt.legend(handles=legend_elements, loc='upper left')
plt.rc('legend', fontsize=30)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment