Seaborn: Place the y-label in a line with the points on the coordinate axis - seaborn

I want to place the y-label in the left upper corner in line with the points on the coordinate axis. The label should replace the axes ticks in that area.
Here is an example from a paper that I read:
I found a lot of information on how to move the label to the top left corner. However, how do I remove the ticks and move the label closer to the axes?

The best solution that I found:
# style
plt.figure(figsize=(8,8))
sns.set_style("white")
sns.set_context("paper", font_scale=1.6)
# plot
sn_dis1 = sns.displot(idx_pix_count_pd, hue='Dataset', x="Size", fill=True, palette='bwr', kind="hist", bins=500)
# y-achses
axes = sn_dis1.axes.flatten()
axes[0].set_ylabel("Count", fontsize=16)
axes[0].yaxis.set_label_coords(.0, .9)
The approach proposed by Trenton (Edit: Who delete his comment to my original question) did not work for me as the text is horizontal vertically. But I learned something from it and am sure that you somehow can make it work like that.
# style
plt.figure(figsize=(8,8))
sns.set_style("white")
sns.set_context("paper", font_scale=1.6)
# plot
sn_dis1 = sns.displot(idx_pix_count_pd, hue='Dataset', x="Size", fill=True, palette='bwr', kind="hist", bins=500)
# y-achses
ticks = range(8)
labels= list(range(7)) + ['Density']
axes = sn_dis1.axes.flatten()
axes[0].set_yticklabels(labels)
# do not show default label
axes[0].get_yaxis().get_label().set_visible(False)

Related

Animated scatter plot with plotly makes an undesired crossing of bubbles

I've done this scatter with plotly express and added an animation. Also, I adjusted the scatter to make it appears as such as a bubble chart. All works great, except for one issue. When I press the button to start the graph animation and one bubble is 'reached' and 'overtaken' by another bubble, they cross each other. By itself, it doesn't create a wrong result, but it's an undesired effect. I've showed the situation in the gif reachable with this link:
https://github.com/TheHextech/start2impact/blob/master/Data_Science/Food_Project_DataVisualization_DataManipulation/normal_animation.gif
However, if I manually drag the spinbox of the animation this effect doesn't show up (check this other link to see the gif https://github.com/TheHextech/start2impact/blob/master/Data_Science/Food_Project_DataVisualization_DataManipulation/dragged_spinbox.gif).
Why does this happen? And how can I fix this problem avoiding the 'overtake' during the normal animation? I share here the entire code of the graph:
fig = px.scatter(
data_frame=chn_food_feed,
x='production',
y='item',
size='production',
size_max=80,
animation_frame='years',
color='element',
color_discrete_map={
'Feed':'brown',
'Food':'orange'},
hover_name='item',
hover_data=dict(
item = False,
element = False),
range_x=[chn_food_feed.production.min()-5000, chn_food_feed.production.max()+50000],
range_y=[-1, 5.5])
fig.update_layout(
title="Storyline of China's top 3 Food and Feed items produced in 2013",
title_x = 0.5,
title_y = 0.95,
title_xanchor='center',
title_yanchor='top',
legend_title_text='Elements',
xaxis = dict(title='Production (1000 tons)'),
yaxis = dict(title=None))
# Speed up the animation
fig.layout.updatemenus[0].buttons[0].args[1]['frame']['duration'] = 250
fig.layout.updatemenus[0].buttons[0].args[1]['transition']['duration'] = 250
fig.show(renderer='notebook_connected') # For VS Code visulization of animation

How to save the image with the red bounding boxes on it detected by mtcnn?

I have this code in which mtcnn detects faces on an image, draws a red rectangle around each face and prints on the screen.
Code taken from: https://machinelearningmastery.com/how-to-perform-face-detection-with-classical-and-deep-learning-methods-in-python-with-keras/
But I want to save the image with the red boxes arround each face. So that i can do some preprocessing on it. Any help is good.
# draw an image with detected objects
def draw_image_with_boxes(filename, result_list):
# load the image
data = pyplot.imread(filename)
# plot the image
pyplot.imshow(data)
# get the context for drawing boxes
ax = pyplot.gca()
# plot each box
for result in result_list:
# get coordinates
x, y, width, height = result['box']
# create the shape
rect = Rectangle((x, y), width, height, fill=False, color='red')
# draw the box
ax.add_patch(rect)
# show the plot
pyplot.show()
filename = 'test1.jpg'
# load image from file
pixels = pyplot.imread(filename)
# create the detector, using default weights
detector = MTCNN()
# detect faces in the image
faces = detector.detect_faces(pixels)
# display faces on the original image
draw_image_with_boxes(filename, faces)
This image so that i can display it on an html
You can use matplotlib.pyplot.savefig. For example:
# save the plot
plt.savefig('image_with_box.jpg')
# show the plot
pyplot.show()
You can find more details here: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.savefig.html

How do I create a categorical legend for imagesc with square legend symbols?

I have with 5 different values and I would like to create a legend ?
These are continuous data, I need small coloured squares !
How to add legend in imagesc plot in matlab Something like this but with squares, I tried replacing "line" by "rectangle" but that's not the trick apparently !
Thank you
I just used your linked example code and modified it a little:
N=4; % # of data types, hence legend entries
Data = randi(N,30,30); % generate fake data
imagesc(Data) % image it
cmap = jet(N); % assigen colormap
colormap(cmap)
hold on
markerColor = mat2cell(cmap,ones(1,N),3);
L = plot(ones(N), 'LineStyle','none','marker','s','visible','off');
set(L,{'MarkerFaceColor'},markerColor,{'MarkerEdgeColor'},markerColor);
legend('A','B','C','D')
The trick is to use markers instead of the line itself.
it returns:

d3 autospace overlapping tick labels

Is there a way in d3 to not draw overlapping tick labels? For example, if I have a bar chart, but the bars are only 5 pixels wide and the labels are 10 pixels wide, I end up with a cluttered mess. I'm currently working on an implementation to only draw the labels when they do not overlap. I can't find any existing way to do that, but wasn't sure if anyone else had dealt with this problem.
There is no way of doing this automatically in D3. You can set the number of ticks or the tick values explicitly (see the documentation), but you'll have to figure out the respective numbers/values yourself. Another option would be to rotate the labels such that there is less chance of them overlapping.
Alternatively, like suggested in the other answer, you could try using a force layout to place the labels. To clarify, you would use the force layout on the labels only -- this is completely independent of the type of chart. I have done this in this example, which is slightly more relevant than the one linked in the other answer.
Note that if you go with the force layout solution, you don't have to animate the position of the labels. You could simply compute the force layout until it converges and then plot the labels.
I've had a similar problem with multiple (sub-)axis, where the last tick overlaps my vertical axis in some situations (depending on the screen width), so I've just wrote a little function that compares the position of the end of the text label with the position of the next axis. This code is very specific to my use case, but could adapted easily to your needs:
var $svg = $('#svg');
// get the last tick of each of my sub-axis
$('.tick-axis').find('.tick:last-of-type').each(function() {
// get position of the end of this text field
var endOfTextField = $(this).offset().left + $(this).find('text').width();
// get the next vertical axis
var $nextAxis = $('line[data-axis="' + $(this).closest('.tick-axis').attr('data-axis') + '"]');
// there is no axis on the very right, so just use the svg width
var positionOfAxis = ($nextAxis.length > 0) ? $nextAxis.offset().left : $svg.offset().left + $svg.width();
// hide the ugly ones!
if (endOfTextField > positionOfAxis) {
$(this).attr('class', 'tick hide');
}
});
The ticks with color: aqua are the hidden ones:

Viewing Part of a figure

I made a simulation of 10000 times and want to view part of simulation between 5000-5200. I am able to view it with the code below, but the x-axis says 0-250. I want the x-axis to display the exact figure of 5000-5200. Also there seems to be a small gap at the end of the figure as the axis runs up to 250 for some reason. I just want to view the figure in for this set time with the x-axis showing the exact labels and without the gap at the end.
Thanks
N=10000;%Number of simulation
P=0.02;
Q = zeros(N,1); %current value of queue
X=zeros(N,1);%simulation data
Ci=0;
L=0.9;
Bu=zeros(N,1);
Bs=30;
Bd1=50;
Bd2=270;
Ti=0;
for Ti=2:N
U=rand(1);
a=log10(U);
b=log10(1-P);
c=(a/b);
d=1+c;
X(Ti)=round(d);
Ci=Ci+1;
if X(Ti)< (L)*(Bs)
Bu(Ti)=Bs;
else if X(Ti) < (L)*(Bs+Bd1)
Bu(Ti)=Bs+Bd1;
else
Bu(Ti)=Bs+Bd1+Bd2;
end
end
Ti=Ti+1;
end
plot(X(5000:5200,1),'r');
set (gca,'ylim',[0 400]);
hold on;
plot(Bu(5000:5200,1),'b');
set (gca,'ylim',[0 400]);
hold off
Plot expects two inputs, the first depicting the horizontal axis and the second depicting the vertical axis. When you do not supply two inputs, then it computes the length of the single input (in this case that length is 5200-5000 = 200), and it just uses 1 through that length (1:200 in this case) as if it is the values for the horizontal axis variable.
I think you want to issue the command:
plot(5000:5200, X(5000:5200,1), 'r')
Often Matlab will adjust plot axes for better default views, so it's probably showing the axis out to the index 250 just by virtue of some default plotting convention. You can similarly use set(gca, 'xlim', [5000 5200]) if you wish.

Resources