Related
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]
This is the current code I have
sns.set_style("whitegrid",{'axes.spines.top': True, 'axes.spines.right': True,'axes.linewidth': 2, 'axes.edgecolor':'black'})
g = sns.JointGrid(x=station1,y=station2,data = df, xlim = xlim, ylim = ylim,space =1)
sns.set_style("whitegrid",{'axes.spines.top': True, 'axes.spines.right': True,'axes.linewidth': 2, 'axes.edgecolor':'black'})
g.plot_joint(sns.regplot, fit_reg = False, truncate = False, robust = False, label = 'regression', color = 'darkorange',)
g.plot_marginals(sns.histplot, kde = True, color = 'darkorange')
# g.ax_joint.legend({'Pearson_R: %.4f'%r, 'x_axis mean:%.3f; std:%.3f'%(d1.df[par_x][idx_1].mean(),d1.df[par_x][idx_1].std()),'y_axis mean:%.3f; std:%.3f'%(d2.df[par_y][idx_2].mean(),d2.df[par_y][idx_2].std())})
# g.ax_joint.legend({'y = %.3f x + %.3f \nR^2: %.4f'%(popt[0],popt[1],r**2)})
g.ax_joint.legend({'$R^2$:%.4f'%(r**2)}, loc = 'upper right')
g.ax_joint.plot(np.linspace(xlim[0],xlim[1],100),linear(np.linspace(xlim[0],xlim[1],100),1,0), linewidth = 0.7, ls = '-.', color = 'black')
I am trying to add spines to Top and left of a joint grid plot in seaborn, However, the best I am able to do is
2 sided plot
is there a way to add a boarder to the top and Right side of the main plot and add right top and left of the sub plots? Thanks.
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
))
I have got three equations involving three parameters
x=u*cos(2*pi*v), y=u*sin(2*pi*v), z=sqrt(1-u^2)*(2*w-1),
where u, v, w belong to [0,1].
How can I draw the graph of above equations using matlab?
I have tried three nested for loops, but it's really time taking. The graph obtained in this way consists of dots and its quality is not so good.
Is there any other way to draw the graph of these equations in Matlab?
You don't need a loop to create the matrix for the calculations. Below is an example for creating the matrices and also plotting. It might not be exactly what you are looking for, but it should get you close.
% set up values to calc for for u,v,w in [0,1]
stepsize = 0.1;
u = 0:stepsize:1; % min, step, max
v = 0:stepsize:1;
w = 0:stepsize:1;
% now set up combined tables
u = u';
v = v';
w = w';
uv = [repmat(u, length(v),1), repmat(v, length(u),1)];
uw = [repmat(u, length(w),1), repmat(w, length(u),1)];
% now do calcs
% note u-vector is uv(:,1) or uw(:,1), depending upon the combo, etc.
x = uv(:,1) .* cos(2 * pi * uv(:,2));
y = uv(:,1) .* sin(2 * pi * uv(:,2));
z = sqrt(1 - uw(:,1) .^2) .* (2 * uw(:,2) -1);
% it's not clear what you want to plot, but here are some examples
figure
hold on
subplot(4,1,1)
plot(x, y, 'Color', 'green', 'DisplayName', 'XY');
box on
title('Your Title Here', 'FontSize', 10)
xlabel('X', 'FontSize', 8)
ylabel('Y', 'FontSize', 8)
set(legend, 'Location', 'best')
subplot(4,1,2)
plot(x, z, 'Color', 'blue', 'DisplayName', 'XZ');
box on
title('Your Title Here', 'FontSize', 10)
xlabel('X', 'FontSize', 8)
ylabel('Z', 'FontSize', 8)
set(legend, 'Location', 'best')
subplot(4,1,3)
plot(y, z, 'Color', 'red', 'DisplayName', 'YZ');
box on
title('Your Title Here', 'FontSize', 10)
xlabel('Y', 'FontSize', 8)
ylabel('Z', 'FontSize', 8)
set(legend, 'Location', 'best')
subplot(4,1,4)
plot3(x, y, z, 'Color', 'magenta', 'DisplayName', 'XYZ');
box on
grid on
ax = gca;
ax.GridAlpha = 0.5;
title('Your Title Here', 'FontSize', 10)
xlabel('X', 'FontSize', 8)
ylabel('Y', 'FontSize', 8)
zlabel('Y', 'FontSize', 8)
set(legend, 'Location', 'best')
The above produces this figure:
I have a string chain of characters that I would like to display as big as possible within a rectangle frame, in a centered way. I know :
how many characters maximum can have my input
the dimensions of the rectangle
It has to :
find the best font size and displays the result.
Here is the MATLAB code
color = 'k';
txt = '1';
howManyCharMaximum = 7;
boxWidth = 250;
boxHeight = 100;
%% comput: Now I assume one char is as wide as tall
howManyChar = strlength(txt);
marginHoriz = mod(boxWidth,howManyCharMaximum); %in points
subRectangle.width = (boxWidth-marginHoriz)/howManyCharMaximum;
subRectangle.height = boxHeight;
[fontSize,idx] = min([subRectangle.width, subRectangle.height]); %the largest square that fits in a rectangle
%%
hFigure = figure('MenuBar', 'none', ...
'ToolBar', 'none', ...
'Units', 'points', ...
'Position', [0 0 boxWidth boxHeight], ... % x y from bottom left of screen to botleft of the fig
'Color', 'w');
hAxes = axes; hAxes.Visible = 'off';
%pos:=botleft vertex of the string
switch(idx)
case 1
x = floor((boxWidth-howManyChar*fontSize)/2);
y = floor((boxHeight-fontSize)/2);
case 2
addMarginHoriz = (subRectangle.width-subRectangle.height)*howManyCharMaximum;
x = floor((boxWidth-howManyChar*fontSize)/2);
y = 0;
end
hText = text(x, y, ...
txt, ...
'Units', 'points', ...
'FontSize', fontSize, ...
'HorizontalAlignment', 'left', ...
'VerticalAlignment', 'middle', ...
'Color', color);
But for some reasons I can't figure out, this is what it returns unfortunately -- a decentered character:
Would anyone know where I did a mistake pleaase ? By thanking you in advance.
I used normalized units for text as its lot easier to find the center and then it worked with the proper alignment. Note that a slight offset will still exist because actual figure grid has more space on left then right and at bottom then top. You can experimentally adjust it if you wish
color = 'k';
txt = '18998';
%howManyCharMaximum = 7; I didnt use this one
boxWidth = 250;
boxHeight = 100;
%% comput: Now I assume one char is as wide as tall
howManyChar = strlength(txt);
%marginHoriz = mod(boxWidth,howManyCharMaximum); %in points
subRectangle.width = (boxWidth)/howManyChar;
subRectangle.height = boxHeight;
[fontSize,idx] = min([subRectangle.width, subRectangle.height]); %the largest square that fits in a rectangle
%%
hFigure = figure('MenuBar', 'none', ...
'ToolBar', 'none', ...
'Units', 'points', ...
'Position', [0 0 boxWidth boxHeight], ... % x y from bottom left of screen to botleft of the fig
'Color', 'w');
hAxes = axes; hAxes.Visible = 'off';
%plot(0,0)
%pos:=botleft vertex of the string
x = floor(boxWidth/2);
y = floor(boxHeight/2)
hText = text(0.5, 0.5, ...
txt, ...
'Units', 'normalized', ...
'FontSize', fontSize, ...
'HorizontalAlignment', 'center', ...
'VerticalAlignment', 'middle', ...
'Color', color);