How to add a scatter plot over a map of London using python - matplotlib-basemap

I am trying to plot this scatter over a map of London, but it is not correct, here is my code, the maps have different sizes and I want one map but I got 2.
This is my dataframe (dfrt) to get the scatter:
commonName id lat lon placeType url additionalProperties2 category key sourceSystemKey value modified
0 River Street , Clerkenwell BikePoints_1 51.529163 -0.109970 BikePoint /Place/BikePoints_1 {'$type': 'Tfl.Api.Presentation.Entities.Addit... Description TerminalName BikePoints 001023 2019-08-22T11:17:04.327Z
1 Phillimore Gardens, Kensington BikePoints_2 51.499606 -0.197574 BikePoint /Place/BikePoints_2 {'$type': 'Tfl.Api.Presentation.Entities.Addit... Description TerminalName BikePoints 001018 2019-08-22T11:10:02.34Z
2 Christopher Street, Liverpool Street BikePoints_3 51.521283 -0.084605 BikePoint /Place/BikePoints_3 {'$type': 'Tfl.Api.Presentation.Entities.Addit... Description TerminalName BikePoints 001012 2019-08-22T11:12:02.7Z
3 St. Chad's Street, King's Cross BikePoints_4 51.530059 -0.120973 BikePoint /Place/BikePoints_4 {'$type': 'Tfl.Api.Presentation.Entities.Addit... Description TerminalName BikePoints 001013 2019-08-22T11:08:02.047Z
4 Sedding Street, Sloane Square BikePoints_5 51.493130 -0.156876 BikePoint /Place/BikePoints_5 {'$type': 'Tfl.Api.Presentation.Entities.Addit... Description TerminalName
And this what I tried to get the plots:
fig = plt.figure(figsize=(20, 10))
m = Basemap(projection='lcc', resolution='h',
lat_0=51.53, lon_0=0.08,
width=1E6, height=1.2E6)
m.shadedrelief()
m.drawcoastlines(color='gray')
m.drawcountries(color='gray')
a4_dims = (20, 10)
fig, ax = plt.subplots(figsize = a4_dims)
ax.scatter(dfrt['lat'], dfrt['lon'])
ax.set_title('Latitud y Longitud de la ubicaciĆ³n de BikePoints')
ax.set_xlabel('Latitud')
ax.set_ylabel('Longitud')
Could you please, help me?

You create figure/axes twice and end up plotting 2 figures. Here is the relevant code based on yours:
# create figure and axes
fig = plt.figure(figsize=(20, 10))
ax1 = plt.gca()
m = Basemap(projection='lcc', resolution='h', \
lat_0=51.53, lon_0=0.08,
width=1E6, height=1.2E6, ax=ax1)
m.shadedrelief()
m.drawcoastlines(color='gray')
m.drawcountries(color='gray')
# a4_dims = (20, 10)
# fig, ax = plt.subplots(figsize = a4_dims)
# uncomment to do scatter plot
#ax1.scatter(dfrt['lat'], dfrt['lon'])
ax1.set_title('Latitud y Longitud de la ubicaciĆ³n de BikePoints')
ax1.set_xlabel('Latitud')
ax1.set_ylabel('Longitud')
plt.show()
and the (unfinish) plot:
Edit 1
For the data plot on the map, here is the code that use simple data to plot:
# sample data
lons = np.array([-5.371475, -1.569707, -0.892185])
lats = np.array([51.211262, 52.819886, 55.122479])
x,y = m(lons, lats)
# any of these code will plot dots on the map
#ax1.plot(*m(lons, lats), 'ro') # OK
#ax1.plot(x, y, 'ro') # OK
ax1.scatter(x, y, 25) # OK
For data from pandas' dataframe, try to get lons and lats as follows:
lons = list(dfrt['lon'])
lats = list(dfrt['lat'])
then do as shown above.

Related

Problem plotting data in Matlab (setting month and year in the x-axis)

I have the following table structure in MATLAB:
Year Month datapoint
1990 1 5
1990 2 7
.
.
.
1995 12 3
I want to plot this with datapoint on y-axis and something like 1990_1, 1990_2... on the x-axis.
How can I go about doing this?
You can format the appearance of the XAxis by getting the handle to that object with the get function, and then modifying the properties directly.
% Create example table
t = table();
t.Year = repelem(1990,72,1);
t.Month = [1:72].';
t.datapoint = [5:76].';
plot(t.datapoint)
% Get x axis
xaxis = get(gca,'XAxis');
% Format tick labels
xaxis.TickLabels = compose('%d_%d',t.Year,t.Month);
% Format interpreter
xaxis.TickLabelInterpreter = 'none';
% Limit number of ticks
xaxis.TickValues = 1:numel(t.datapoint);
As per your comment, to only see every 12th label:
indx = 1:72;
indx(12:12:72) = 0;
indx(indx > 1) = 1;
xaxis.TickLabels(find(indx)) = {''}

Remove spacing in matlab subplot in odd/even vector

Im new in Matlab. I tried to subplot multiple images using previous example on this problem and it works. However, it shows 5x5 array insted of 5x6 array. What if the number of images(case of study im on right now) are odd? How to plot images based on odd number of array? Here is my code. Please help me.Any help is greatly appreciated
1. figure;
2. for n=1:30
3. filename= fullfile(input_dir,filenames(n).name);
4. img = imread(filename);
5. img1 = imcrop(img,[79 90 95 127]);
6. img2=histeq(img1);
7.
8. I = img2;
9. A = imnoise(I,'salt & pepper',0.01);
10. A=double(A);
11. [ imf_matrix ] = bemd( A );
12. imf1 = imf_matrix(:,:,1);
13.a = mat2gray(imf1);
14.subplot('Position',[(mod(n-1,5))/5 1-(ceil(n/5))/5 1/5 1/5]),imshow(a);
15.
16.
17.
18. anger(:,n) = imf1(:);
19.
20.
21.
22.end
23.p = get(gcf,'Position');
24.k = [size(a,2) size(a,1)]/(size(a,2)+size(a,1));
25.set(gcf,'Position',[p(1) p(2) (p(3)+p(4)).*k])
26.
27.an=anger';
Here is my resultsalt and pepper at 10% noise density
you had a problem with your bottom part of the 'Position':
for ii = 1:30
im = im2double(imread('cameraman.tif'));
im = imresize(im,[40 30]);
a = imrotate(im,randi(360),'bilinear','crop');
left = (mod(ii-1,5))/5;
bottom = (floor((ii-1)/5))/6;
% or: bottom = 5/6 - (floor((ii-1)/5))/6;
subplot('Position',[left, bottom, 1/5, 1/6]);
end
however, you can also do it like that:
for ii = 1:30
im = im2double(imread('cameraman.tif'));
im = imresize(im,[40 30]);
a = imrotate(im,randi(360),'bilinear','crop');
if ii == 1
A = zeros(size(a,1)*6,size(a,2)*5);
end
row = floor((ii - 1)/5);
col = mod(ii - 1,5);
A((1:40) + row*40,(1:30) + col*30) = a;
end
figure;
imshow(A)

PCA with colorbar

I have this data of which I want to make a principal component analysis.
In particular for each data point I want to associate a color.
This is my code:
for ii=1:size(SBF_ens,1)
SBF(ii) = SBF_ens(ii, max(find(SBF_ens(ii,:)~=0)) ); %value at the moment of the measurement
end
%matrix of data
toPCA =[
wind_trend_72h_ens-nanmean(wind_trend_72h_ens);
wind_trend_24h_ens-nanmean(wind_trend_24h_ens);
wind_trend_12to18h_ens-nanmean(wind_trend_12to18h_ens);
wind_trend_0to12h_ens-nanmean(wind_trend_0to12h_ens);
wind_trend_last6h_ens-nanmean(wind_trend_last6h_ens);
Mwind12h_ens-nanmean(Mwind12h_ens);
Mwind24h_ens-nanmean(Mwind24h_ens);
SBF-nanmean(SBF)]';
variables = { 'wt72h','wt24h','wt12to18h','wt0to12h','wtLast6h','Mw12h', 'Mw24h', 'SBF'}; %labels
%PCA algorithm
C = corr(toPCA,toPCA);
w = 1./var(toPCA);
[wcoeff,score,latent,tsquared,explained] = pca(toPCA,'VariableWeights',w);
coefforth = diag(sqrt(w))*wcoeff;
metric=decstd_ens; %metric for colorbar
hbi=biplot(coefforth(:,1:2),'scores',score(:,1:2),'varlabels',...
variables,'ObsLabels', num2str([1:length(toPCA)]'),...
'markersize', 15);
%plotting
cm = autumn;
colormap(cm);
for ii = length(hbi)-length(toPCA):length(hbi)
userdata = get(hbi(ii), 'UserData');
if ~isempty(userdata)
indCol = ceil( size(cm,1) * abs(metric(userdata))/max(abs(metric)) );%maps decstd between 0 and 1 and find the colormap index
if indCol==0 %just avoid 0
indCol=1;
end
col = cm(indCol,:); %color corresponding to the index
set(hbi(ii), 'Color', col); %modify the dot's color
end
end
for ii = 1:length(hbi)-length(toPCA)-1 %dots corresponding to the original dimensions are in black
set(hbi(ii), 'Color', 'k');
end
c=colorbar;
ylabel(c,'decstd') %is this true?
xlabel(['1^{st} PCA component ', num2str(explained(1)), ' of variance explained'])
ylabel(['2^{nd} PCA component ', num2str(explained(2)), ' of variance explained'])
The resulting figure is the following:
Everything is fine except for the colorbar range. In fact decstd has values between 0 and 2. Actually I do not understand at all what the values on the colorbar are.
Does anyone understand it?
Is it possible to rethrive the data in the colorbar? So to understand what they are?
size(autumn)
shows you that the default length of the autumn colourmap (actually of all the colourmaps) is 64. When you call colorbar, by default it will use tick labels from 1 to n where n is the length of your colourmap, in this case 64.
If you want the mapping of the colourbar ticklabels to match the mapping that you used to get your data to fit between 1 and 64 (i.e. this line of yours indCol = ceil( size(cm,1) * abs(metric(userdata))/max(abs(metric)) );), then you will need to set that yourself like this
numTicks = 6;
cAxisTicks = linspace(min(metric), max(metric), numTicks); % or whatever the correct limits are for your data
caxis([min(metric), max(metric)]);
set(c,'YTick', cAxisTicks );

How to draw a group by boxplot in matlab

I have a three groups such as
Group 1={x1,x2}
x1=[1,2,2,3,5,3]
x2=[2,5,4,5,8,6]
Group 2={x3,x4}
x3=[2,8,9,2,1,6]
x4=[5,4,3,22,11,6]
Group 2={x5,x6}
x5=[10,12,22,4]
x6=[12,15,4,25]
I want to draw them into char by boxplot function by group. I found the way to resolve it. But it cannot draw. Could you help me please?
x1=[1,2,2,3,5,3];
x2=[2,5,4,5,8,6];
g1={x1,x2};
%group2
x3=[2,8,9,2,1,6];
x4=[5,4,3,22,11,6];
g2={x3,x4};
%group3
x5=[10,12,22,4];
x6=[12,15,4,25];
g3={x5,x6};
G=cat(1,g1,g2,g3);
class={1,2,3}
positions = [1 1.25 2 2.25 3 3.25];
boxplot(G,class, 'positions', positions);
set(gca,'xtick',[mean(positions(1:2)) mean(positions(3:4)) mean(positions(5:6)) ])
set(gca,'xticklabel',{'Group1','Group2','Group3'})
color = ['c', 'y', 'c', 'y'];
h = findobj(gca,'Tag','Box');
for j=1:length(h)
patch(get(h(j),'XData'),get(h(j),'YData'),color(j),'FaceAlpha',.5);
end
c = get(gca, 'Children');
hleg1 = legend(c(1:2), 'Feature1', 'Feature2' );
Your problem is that the grouping variables were constructed in the wrong way. Use this sample:
x1=[1,2,2,3,5,3];
x2=[2,5,4,5,8,6];
g1=[x1,x2];
v1=[repmat('A',1,numel(x1)),repmat('B',1,numel(x2))];
%group2
x3=[2,8,9,2,1,6];
x4=[5,4,3,22,11,6];
g2=[x3,x4];
v2=[repmat('A',1,numel(x3)),repmat('B',1,numel(x4))];
%group3
x5=[10,12,22,4];
x6=[12,15,4,25];
g3=[x5,x6];
v3=[repmat('A',1,numel(x5)),repmat('B',1,numel(x6))];
%%
G=[g1,g2,g3]
vg1 = [repmat('1',1,numel(v1)),repmat('2',1,numel(v2)),repmat('3',1,numel(v3))];
vg2=[v1,v2,v3] ;
%%
clc
boxplot(G', {vg1';vg2'}, 'factorseparator',1 , 'factorgap',30,...
'colorgroup',vg2','labelverbosity','majorminor');

Most efficient way of drawing grouped boxplot matlab

I have 3 vectors: Y=rand(1000,1), X=Y-rand(1000,1) and ACTid=randi(6,1000,1).
I'd like to create boxplots by groups of Y and X corresponding to their group value 1:6 (from ACTid).
This is rather ad-hoc and looks nasty
for ii=
dummyY(ii)={Y(ACTid==ii)};
dummyX(ii)={X(ACTid==ii)}
end
Now I have the data in a cell but can't work out how to group it in a boxplot. Any thoughts?
I've found aboxplot function that looks like this but I don't want that, I'd like the builtin boxplot function because i'm converting it to matlab2tikz and this one doesn't do it well.
EDIT
Thanks to Oleg: we now have a grouped boxplot... but the labels are all skew-whiff.
xylabel = repmat({'Bleh','Blah'},1000,1); % need a legend instead, but doesn't appear possible
boxplot([Y(:,end); cfu], {repmat(ACTid,2,1), xylabel(:)} ,'factorgap',10,'color','rk')
set(gca,'xtick',1.5:3.2:50)
set(gca,'xticklabel',{'Direct care','Housekeeping','Mealtimes','Medication','Miscellaneous','Personal care'})
>> ylabel('Raw CFU counts (Y)')
How to add a legend?
I had the same problem with grouping data in a box plot. A further constraint of mine was that different groups have different amounts of data points. Based on a tutorial I found, this seems to be a nice solution I wanted to share with you:
x = [1,2,3,4,5,1,2,3,4,6];
group = [1,1,2,2,2,3,3,3,4,4];
positions = [1 1.25 2 2.25];
boxplot(x,group, 'positions', positions);
set(gca,'xtick',[mean(positions(1:2)) mean(positions(3:4)) ])
set(gca,'xticklabel',{'Direct care','Housekeeping'})
color = ['c', 'y', 'c', 'y'];
h = findobj(gca,'Tag','Box');
for j=1:length(h)
patch(get(h(j),'XData'),get(h(j),'YData'),color(j),'FaceAlpha',.5);
end
c = get(gca, 'Children');
hleg1 = legend(c(1:2), 'Feature1', 'Feature2' );
Here is a link to the tutorial.
A two-line approach (although if you want to retain two-line xlables and center those in the first line, it's gonna be hackish):
Y = rand(1000,1);
X = Y-rand(1000,1);
ACTid = randi(6,1000,1);
xylabel = repmat('xy',1000,1);
boxplot([X; Y], {repmat(ACTid,2,1), xylabel(:)} ,'factorgap',10)
The result:
EDIT
To center labels...
% Retrieve handles to text labels
h = allchild(findall(gca,'type','hggroup'));
% Delete x, y labels
throw = findobj(h,'string','x','-or','string','y');
h = setdiff(h,throw);
delete(throw);
% Center labels
mylbl = {'this','is','a','pain','in...','guess!'};
hlbl = findall(h,'type','text');
pos = cell2mat(get(hlbl,'pos'));
% New centered position for first intra-group label
newPos = num2cell([mean(reshape(pos(:,1),2,[]))' pos(1:2:end,2:end)],2);
set(hlbl(1:2:end),{'pos'},newPos,{'string'},mylbl')
% delete second intra-group label
delete(hlbl(2:2:end))
Exporting as .png will cause problems...