How I can increase the x, y tick label font size in seaborn heatmap subplots? [duplicate] - seaborn

This question already has an answer here:
seaborn how to set style and font size
(1 answer)
Closed 5 months ago.
Hello How I can increase the x, y tick label font size in seaborn heatmap subplots?
I wanna have pretty good balanced label and title size between subplots
My current coding is like the below.
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(20,7))
# Singular office
A = sns.heatmap(data =corr_CO2_R_VC_SingularOffice, ax=axes[0], mask=mask4, cmap=cmap, vmax=1.0, vmin=-0.3, center=0,
square=True, linewidths=.5, cbar_kws={"shrink": .5}
, annot=True, cbar = False, fmt=".1f",annot_kws={"size": 14})
# Openplan office
B = sns.heatmap(corr_CO2_R_VC_OpenplanOffice, ax=axes[1], mask=mask5, cmap=cmap, vmax=1.0, vmin=-0.3, center=0,
square=True, linewidths=.5, cbar_kws={"shrink": .5}
, annot=True, cbar = False, fmt=".1f",annot_kws={"size": 14})
# MultiR
C = sns.heatmap(corr_CO2_R_VC_MultiR, ax=axes[2], mask=mask6, cmap=cmap, vmax=1.0, vmin=-0.3, center=0,
square=True, linewidths=.5, cbar_kws={"shrink": .5}
, annot=True, fmt=".1f",annot_kws={"size": 14})
# Spacing
plt.subplots_adjust(left= 0.11, bottom=0.35, right=0.9, top=0.7, wspace=0.1, hspace=0.1)
#xtick label name change
A.set_yticklabels(['People_count','VC_singularoffice','Wall','Desk','Entrance'])
A.set_xticklabels(['People_count','VC_singularoffice','Wall','Desk','Entrance'])
B.set_yticklabels(['People_count','VC_openplanoffice','Wall','Desk','Entracne'])
B.set_xticklabels(['People_count','VC_openplanoffice','Wall','Desk','Entracne'])
C.set_yticklabels(['People_count','VC_MultiR','Wall','Desk','Entrance'])
C.set_xticklabels(['People_count','VC_MultiR','Wall','Desk','Entrance'])
#common title
fig.suptitle('CO2 & Occupancy', fontsize = 18)
#sub title
A.set_title("Singular office", fontsize=16)
B.set_title("Openplan office ", fontsize=16)
C.set_title("MultiR", fontsize=16)
plt.tight_layout()
plt.show()
x, ytick label size is too small

Have you tried this possible solution out?
e.g.:
A.set_yticklabels(A.get_yticks(), size = 15)

Related

How to create subplots with seaborn? I am not achieving my expected result [duplicate]

This question already has an answer here:
seaborn is not plotting within defined subplots
(1 answer)
Closed 6 months ago.
I am trying to create a simple subplot in seaborn using 1 row 2 columns. But am not getting the expected result. Instead my figures are displaying separately. Please help.
df = sns.load_dataset("tips")
fig, axes = plt.subplots(nrows = 1, ncols = 2, figsize = (15,6))
sns.relplot(x = "tip", y= "total_bill" , data = df , hue = "smoker", kind = "line",
hue_order = ["No", "Yes"], ax = axes[0])
sns.catplot(x = "tip", data = df, kind = "point", ax = axes[1])
Result
Both the plots you are using - relplot and catplot are figure level plots. They cannot be used as sub plots. That is the reason you are seeing the initial blank plots and then the individual relplot and catplot.
You need to use lineplot and pointplot respectively instead, which will allow you to use the subplots. Note that kind='line' is no longer required, so it has been commented out in the code below...
df = sns.load_dataset("tips")
fig, axes = plt.subplots(nrows = 1, ncols = 2, figsize = (15,6))
sns.lineplot(x = "tip", y= "total_bill" , data = df , hue = "smoker", #kind = "line",
hue_order = ["No", "Yes"], ax = axes[0])
sns.pointplot(x = "tip", data = df, kind = "point", ax = axes[1])
Plot

Fix aspect ratio of a scatter plot with an image

I've to plot multiple scatter and table in a grid space and I'm having a couple of issues with the relative position but most important with defining and maintaining the aspect ratio of the scatter plot.
I've written a script with "fake" data on it to describe my problem and a minimum "not working" example below.
What I have is a dataframe with x, and y positions of objects, and what I want to do is to put the corresponding image below.
Since the image can have an arbitrary aspect ratio I need to read the aspect ratio and construct the scatter plot in that way but I'm unable to make it work.
Another problem is connected with the invert_xaxis and invert_yaxis that don't work (I need that command since the scatter data are inverted.
I've used the following commands, and as far as I've understood each of them should block the aspect ratio of the scatter plot to the same ratio of the figure but they do not work.
The aspect ratio becomes corrected only when the figure is plotted but that eliminates the effect of axis inversion.
I've had a similar problem with setting the aspect ratio of plots without the addition of a figure, sometimes it worked but not with tight_layout.
It is obvious that I'm missing something important....but I'm unable to figure it out.
This is the fake data code:
###############################################################################
# fake data
#general data aspect ratio
image_height= 5 #4270
image_width = 10 # 8192
pix2scale = 0.3125
data_AR = image_height / image_width
#random data generation
data_width = image_width* pix2scale
data_height = image_height * pix2scale
data1x = np.random.uniform(-data_width/2, data_width/2, size=(40))
data1y = np.random.uniform(-data_height/2, data_height/2, size=(40))
data2x = np.random.uniform(-data_width/2, data_width/2, size=(40))
data2y = np.random.uniform(-data_height/2,data_height/2, size=(40))
temp_df1 = pd.DataFrame([data1x,data1y,['random1']*40],index = ['x','y','label']).T
temp_df2 = pd.DataFrame([data2x,data2y,['random2']*40],index = ['x','y','label']).T
df = pd.concat([temp_df1,temp_df2],axis = 0, ignore_index = True)
del temp_df1, temp_df2
#sample image generation of variable aspect ratio
img_size = (image_height, image_width)
R_layer = np.ones(shape= img_size)*0.50
G_layer = np.ones(shape= img_size)*0.50
B_layer = np.ones(shape= img_size)*0.50
A_layer = np.ones(shape= img_size)
img = np.dstack([R_layer,G_layer,B_layer,A_layer])
#add a mark at the top left of the image
for k in range(0,3):
for i in range(0,int(image_width*0.2*data_AR)):
for j in range(0,int(image_width*0.2)):
img[i,j,k] = 0
#add a mark at the center of the image
# get center coordinates of the image
center = [[2, 4], [2, 5]]
for k in range(0,3):
for point in center:
if k == 0:
img[point[0],point[1],k] = 1
else:
img[point[0],point[1],k] = 0
#show image
fig, ax = plt.subplots()
ax.imshow(img)
###############################################################################
this is the code that generates the image:
#%%
# sample code
# at this point IƬve already loaded the image, the pix2scale value
# and the df containing data points
#read image aspect ratio
img_AR = img.shape[0]/img.shape[1]
pixel_width = img.shape[1]
pixel_height = img.shape[0]
# each pixel correspond to 0.3125 unit (mm)
pix2scale = 0.3125
#define image position
#the center of the image need to be placed at (0,0)
#bottom left corner
left = - (pixel_width * pix2scale)/2
bottom = - (pixel_height * pix2scale)/2
right = left + (pixel_width * pix2scale)
top = bottom + (pixel_height * pix2scale)
extent = [left,right,bottom,top]
#figure definition
figure_width = 15 #inch
figure_AR = 1
scatter_AR = img_AR
#initialize figure
fig_s= plt.figure(figsize = (figure_width,figure_width*figure_AR))
gs = plt.GridSpec (3,3)
#scatter plot in ax1
ax1 = fig_s.add_subplot(gs[:2,:2])
g = sns.scatterplot( data = df,
x = 'x',
y = 'y',
hue = 'label',
ax =ax1
)
ax1.invert_xaxis()
ax1.invert_yaxis()
#resize the figure box
box = ax1.get_position()
ax1.set_position([box.x0,box.y0,box.width*0.4,box.width*0.4*scatter_AR])
ax1.legend(loc = 'center left', bbox_to_anchor = (1,0.5))
ax1.set_title('Inclusions Scatter Plot')
ax1.set_aspect(scatter_AR)
#plt image
ax1.imshow(img,extent = extent)
#scatter plot
ax2 = fig_s.add_subplot(gs[2,:2])
g = sns.scatterplot( data = df,
x = 'x',
y = 'y',
hue = 'label',
ax =ax2
)
#resize the figure box
box = ax2.get_position()
ax2.set_position([box.x0,box.y0,box.width*0.4,box.width*0.4*scatter_AR])
ax2.legend(loc = 'center left', bbox_to_anchor = (1,0.5))
ax2.set_title('Inclusions Scatter Plot')
ax2.set_aspect(scatter_AR)
ax2.imshow(img,extent = extent)
#scatter plot
ax3 = fig_s.add_subplot(gs[1,2])
g = sns.scatterplot( data = df,
x = 'x',
y = 'y',
hue = 'label',
ax =ax3
)
#resize the figure box
box = ax3.get_position()
ax3.set_position([box.x0,box.y0,box.width*0.4,box.width*0.4*scatter_AR])
ax3.legend(loc = 'center left', bbox_to_anchor = (1,0.5))
ax3.set_title('Inclusions Scatter Plot')
ax3.set_aspect(scatter_AR)
ax3.imshow(img,extent = extent)
#add suptitle to figure
fig_s.suptitle('my title',fontsize= 22)
fig_s.subplots_adjust(top=0.85)
# #make it fancy
for i in range(3):
fig_s.tight_layout()
plt.pause(0.2)
I've plotted multiple grid because I wanted to test the tight_layout().
[enter image description here][2]

Facebook DETR resnet 50 in HuggingFace Hub

Trying the pretrained Faceboook DETR model for object detection using the HuggingFace implementation.
The sample code listed below from https://huggingface.co/facebook/detr-resnet-50 is straightforward.
from transformers import DetrFeatureExtractor, DetrForObjectDetection
from PIL import Image
import requests
import numpy as np
url = 'http://images.cocodataset.org/val2017/000000039769.jpg'
image = Image.open(requests.get(url, stream=True).raw)
feature_extractor = DetrFeatureExtractor.from_pretrained('facebook/detr-resnet-50')
model = DetrForObjectDetection.from_pretrained('facebook/detr-resnet-50')
inputs = feature_extractor(images=image, return_tensors="pt")
outputs = model(**inputs)
# model predicts bounding boxes and corresponding COCO classes
logits = outputs.logits
bboxes = outputs.pred_boxes
I can use
threshod = 0.7
labels =['background', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
'train', 'truck', 'boat', 'traffic light', 'fire hydrant',
'street sign', 'stop sign', 'parking meter', 'bench', 'bird',
'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra',
'giraffe', 'hat', 'backpack', 'umbrella', 'shoe', 'eye glasses',
'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard',
'sports ball', 'kite', 'baseball bat', 'baseball glove',
'skateboard', 'surfboard', 'tennis racket', 'bottle', 'plate',
'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana',
'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog',
'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',
'mirror', 'dining table', 'window', 'desk', 'toilet', 'door', 'tv',
'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave',
'oven', 'toaster', 'sink', 'refrigerator', 'blender', 'book',
'clock', 'vase', 'scissors', 'teddy bear', 'hair drier',
'toothbrush']
np_softmax = (logits.softmax(-1)[0, :, :-1]).detach().numpy()
classes = []
probability = []
idx = []
for i, j in enumerate(np_softmax):
if np.max(j) > threshold:
classes.append(labels[np.argmax(j)])
probability.append(np.max(j))
idx.append(i)
to retrieve the detected classes. But I did not fully understand the coordinates in the bboxes.
This is a torch tensor with 100 bounded boxes coordinates of 4 dimensions. With idx I can get the index of the classes so I can get their corresponding boxes. Seems the coordinates are normalized because they are all between 0 and 1. I have a difficulty to remap the coordinates into pixels so I can draw the bounded boxes on the original images. Could not find documentation on this, any suggestions? Thanks
Okay, figured it out, the four coordinates are the normalized (X center, Y center, Width, Height)
if you want to draw a rectangle for each bbox you can use this code:
plt.figure(figsize=(16,10))
plt.imshow(pil_img)
ax = plt.gca()
(xmin, ymin, xmax, ymax) = bbox
ax.add_patch(plt.Rectangle(
(xmin, ymin),
xmax - xmin,
ymax - ymin,
fill = False,
color = c,
linewidth = 3
))

PIL.ImageDraw.ImageDraw.text features attribute in Pillow 7.0.0 dosen't seem to give any difference in results

This is the code
img = np.full(shape=(40, 225, 3), fill_value=211, dtype=np.uint8)
b,g,r,a = 0,0,0,0
fontpath = "arial.ttf"
font = ImageFont.truetype(fontpath, 14)
img_pil = Image.fromarray(img)
draw = ImageDraw.Draw(img_pil)
draw.text((25, 10), captcha, font=font, features=['cpsp', 'dist'], fill=(b, g, r, a))
# w=img_pil.rotate(17.5, expand=1)
# img_pil = Image.paste( ImageOps.colorize(w, (0,0,0), (255,255,84)), (242,60), w)
img = np.array(img_pil)
noise_factor = np.random.uniform(low=0.4, high=0.8, size=1)
gauss = np.random.normal(0, noise_factor, img.size)
gauss = gauss.reshape(img.shape[0],img.shape[1],img.shape[2]).astype('uint8')
noise = img + img * gauss
## Display
gray = cv2.cvtColor(noise, cv2.COLOR_BGR2GRAY)
cv2.imwrite(captcha+".png", gray)
The above code didn't alter the space between the characters, am I using it right?
Please include some examples in https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html on how to use this.
Click Here to see the output for the above code

Matplotlib Animation: updating radial view limit for polar plot

I'm trying to create an animated polar plot that, where the radial view limit increases/decreases to accommodate the radius. The yaxis updates just fine if I set polar=False, but it doesn't work correctly for a polar axis.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def data_gen():
t = data_gen.t
cnt = 0
while cnt < 1000:
cnt+=1
t += 0.05
yield t, 1.1 + np.sin(2*np.pi*t) * np.exp(t/10.)
data_gen.t = 0
plt.rc ('grid', color='g', lw=1, ls='-')
plt.rc ('xtick', labelsize=15, color='b')
plt.rc ('ytick', labelsize=15, color='b')
fig = plt.figure(figsize=(8,8))
ax1 = fig.add_axes([.05, .90, .9, .08], polar=False, axisbg='#BFBFBF', xticks=[], yticks=[])
ax2 = fig.add_axes([.05, .05, .9, .8], polar=True, axisbg='k')
#ax = fig.add_axes([.1,.1,.8,.8], polar=False, axisbg='k')
line, = ax2.plot([], [], lw=2)
ax2.set_ylim(0, 2.2)
ax2.set_xlim(0, 140)
ax2.grid(1)
xdata, ydata = [], []
title = ax1.text (0.02, 0.5, '', fontsize=14, transform=ax1.transAxes)
def init():
line.set_data([], [])
title.set_text ('')
return line, title
def run(data):
# update the data
t,y = data
xdata.append(t)
ydata.append(y)
ymin, ymax = ax2.get_ylim()
if y >= ymax:
ax2.set_ylim (ymin, 2*ymax)
ax2.figure.canvas.draw()
title.set_text ("time = %.3f, y(t) = 1.1 + sin(2*pi*t) + exp(t/10) = %.3f" % (t, y))
line.set_data(xdata, ydata)
return line, title
ani = animation.FuncAnimation(fig, run, data_gen, init, blit=True, interval=100, repeat=False)
Actually, the view limit does adjust, but the tick labels stay the same. Inserting raw_input() after the canvas is redrawn reveals that everything is redrawn correctly, but then the tick labels revert back to what they were before. Stranger still, this doesn't occur until the update() function is called a second time and returns.
I didn't have this problem when I animated the plot the old way, by calling draw() repeatedly. But I'd rather do it the right way with the animation module, as the old way had performance problems (The above code block is only to demonstrate the problem, and isn't the actual program that I'm writing).
I should note that I'm still learning MPL, so I apologize if some of my terminology is wrong.
If you use blit, the background is saved in cache for fast draw, you can clear the cache when the axis range is changed, add ani._blit_cache.clear():
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def data_gen():
t = data_gen.t
cnt = 0
while cnt < 1000:
cnt+=1
t += 0.05
yield t, 1.1 + np.sin(2*np.pi*t) * np.exp(t/10.)
data_gen.t = 0
plt.rc ('grid', color='g', lw=1, ls='-')
plt.rc ('xtick', labelsize=15, color='b')
plt.rc ('ytick', labelsize=15, color='b')
fig = plt.figure(figsize=(8,8))
ax1 = fig.add_axes([.05, .90, .9, .08], polar=False, axisbg='#BFBFBF', xticks=[], yticks=[])
ax2 = fig.add_axes([.05, .05, .9, .8], polar=True, axisbg='k')
#ax = fig.add_axes([.1,.1,.8,.8], polar=False, axisbg='k')
line, = ax2.plot([], [], lw=2)
ax2.set_ylim(0, 2.2)
ax2.set_xlim(0, 140)
ax2.grid(1)
xdata, ydata = [], []
title = ax1.text (0.02, 0.5, '', fontsize=14, transform=ax1.transAxes)
def init():
line.set_data([], [])
title.set_text ('')
return line, title
def run(data):
# update the data
t,y = data
xdata.append(t)
ydata.append(y)
ymin, ymax = ax2.get_ylim()
if y >= ymax:
ax2.set_ylim (ymin, 2*ymax)
ani._blit_cache.clear() # <- add to clear background from blit cache
title.set_text('') # <- eliminate text artifact in title
ax2.figure.canvas.draw()
title.set_text ("time = %.3f, y(t) = 1.1 + sin(2*pi*t) + exp(t/10) = %.3f" % (t, y))
line.set_data(xdata, ydata)
return line, title
ani = animation.FuncAnimation(fig, run, data_gen, init, blit=True, interval=100, repeat=False)

Resources