Related
I have a collection of data that I am trying to graph as a histogram. Additionally, I would like to color the individual bars as a function of the x axis location. CData, described here seems to do what I want but I can't get it to work.
Here is my code:
h = bar(new_edge,N,'hist','FaceColor','flat');
hold on
for n = 1:length(N)
if (x - x/1.09) - (x-1) > 0
probability(n) = 1 - ((x-x/1.09) - (x-1))/((x - 1/1.09)+(x/0.91 - x));
else
probability(n) = 1;
end
color_num = 30;
cm = jet(color_num);
min = 0.5450;
max = 1;
color_map_index = floor(1 + (probability(n) - min)/(max-min)*(color_num-1));
rbg = cm(color_map_index,:);
h.CData(n,:) = rbg;
end
Similar to the MATLAB example, I first create my bar graph. Next, I want to loop through and prescribe the color for each bar based on a calculation. I do this by creating a colormap with # of bins and a min/max, getting a color index, then finally retrieving the rbg value. I get the following error when I try to apply the color:
Subscript indices must either be real positive integers or logicals.
h.CData(n,:) = rbg;
If I dive into the h object, MATLAB tells me that CData has a size of (4x65). What's going on here? Both new_edge and N are 1x65 vectors.
Are you certain that the error you're getting ("Subscript indices must either be real positive integers or logicals") is coming from the following line?:
h.CData(n,:) = rbg;
Since we know n is a positive integer greater than or equal to one, the indexing here shouldn't have a problem. It's more likely that your error is coming from the line above it (i.e. the value for color_map_index is less than 1). I would double-check how you are computing color_map_index.
You could also try using function notation (i.e. get and set) instead of dot notation to update the property:
cData = get(h, 'CData');
cData(n, :) = rbg;
set(h, 'CData', cData);
Incidentally, you should also not be giving your variables the same name as existing functions, like you are doing here:
...
min = 0.5450;
max = 1;
...
This shadows the built-in min and max functions, which can also lead to the same error message under other conditions. Definitely rename those.
If you are still having trouble after trying those fixes, you could try setting the color using indexed color mapping instead, as illustrated in one of my other answers (near the bottom). As a simple example, the following plots 20 bars of 30 different possible values, then colors them based on their height:
color_num = 30;
N = randi(color_num, 1, 20);
hBar = bar(N, 'hist');
colormap(parula(color_num));
set(hBar, 'CData', N, 'CDataMapping', 'direct');
And the plot:
This could be a problem with your Matlab version.
When I test CData with bar on 2017b, this works:
openExample('graphics/ControlIndividualBarColorsExample')
When I try it on 2017a, it doesn't run.
Does the example work?
Given that this is a version control problem, there's really not a clean solution. In case anyone else comes along with a similar question and has the same version, here's a workaround that worked for me in 2017a.
Rather than creating a bar chart, you can simply draw rectangles. It's messy, but it does produce the desired result.
[N,edges] = histcounts(AB(AB<2));
probability = zeros(1,length(N));
new_edge = zeros(1,length(N));
for m = 1:length(N)
new_edge(m) = (edges(m) + edges(m+1))/2;
end
figure
hold on
for n = 1:length(N)
x = new_edge(n);
if ((x - x/1.09) - (x-1)) > 0
probability(n) = 1 - ((x-x/1.09) - (x-1))./((x - x/1.09)+(x/0.91 - x));
else
probability(n) = 1;
end
color_num = 100;
cm = jet(color_num);
min = 0;
max = 1;
color_map_index(n) = floor(1 + (probability(n) - min)/(max-min)*(color_num-1));
rbg = cm(color_map_index(n),:);
rectangle('Position',[edges(n),0,(edges(n+1)-edges(n)),N(n)],'Edgecolor','k','FaceColor',rbg)
end
set(gcf,'color','w');
blah = colorbar;
I'm trying to plot streamlines of u and v wind speed components and latitude and longitude 2-d arrays overlaid on an outline of a USA map with geoshow (hence the USA outlat and outlon lat/lon coordinates). My data looks like this with 4 variables: outlat, outlon, u and v are all 5 X 5 arrays to make it easy. Despite all the examples i've seen online I do not understand how the outlat and outlon values relate to the startx or X and starty or Y starting points. My 4 variable data looks like this:
outlat =
17.4154 17.4862 17.5570 17.6278 17.6986
17.4406 17.5114 17.5822 17.6530 17.7239
17.4657 17.5365 17.6074 17.6783 17.7492
17.4908 17.5616 17.6325 17.7034 17.7744
17.5157 17.5866 17.6576 17.7285 17.7995
outlon =
-126.6557 -126.6822 -126.7086 -126.7352 -126.7617
-126.5816 -126.6079 -126.6344 -126.6608 -126.6874
-126.5074 -126.5337 -126.5600 -126.5865 -126.6129
-126.4331 -126.4594 -126.4857 -126.5120 -126.5384
-126.3588 -126.3850 -126.4113 -126.4375 -126.4639
u =
4.3284 4.2194 4.1311 4.1058 4.1257
4.2915 4.1725 4.1192 4.0914 4.1078
4.2893 4.1729 4.0948 3.9822 3.9411
4.3015 4.1781 4.0060 3.5111 3.2246
4.3201 4.1979 3.9442 2.6250 2.0477
v =
7.6193 7.5646 7.5514 7.5293 7.4777
7.5880 7.5226 7.4864 7.4412 7.3617
7.5464 7.5055 7.4640 7.3788 7.1708
7.4983 7.4718 7.4614 7.4554 6.9534
7.4479 7.4317 7.4620 7.8292 7.6354
After trying lots of different attempts, I've tried this now and keep getting a BLANK figure with a USA states map and no streamlines with this MATLAB code using meshgrid as follows:
figure
ax = usamap('conus');
set(ax, 'Visible','off'); setm(ax,'mapprojection','lambert');
states = shaperead('usastatelo','UseGeoCoords', true, 'BoundingBox',... [dlonlim', dlatlim']);
geoshow(states, 'FaceColor', [1 1 1],'facealpha',0);
hold on;
x = linspace(0,10,5); y = linspace(0,10,5);
[X,Y] = meshgrid(x,y);
streamline(outlat,outlon,u,v,X,Y);
Do I need to use stream2 to help calculate the streamline? I've tried quiver and got results but I need a streamline plot. Thank you in advance!
I am optimizing portfolio of N stocks over M levels of expected return. So after doing this I get the time series of weights (i.e. a N x M matrix where where each row is a combination of stock weights for a particular level of expected return). Weights add up to 1.
Now I want to plot something called portfolio composition map (right plot on the picture), which is a plot of these stock weights over all levels of expected return, each with a distinct color and length (at every level of return) is proportional to it's weight.
My questions is how to do this in Julia (or MATLAB)?
I came across this and the accepted solution seemed so complex. Here's how I would do it:
using Plots
#userplot PortfolioComposition
#recipe function f(pc::PortfolioComposition)
weights, returns = pc.args
weights = cumsum(weights,dims=2)
seriestype := :shape
for c=1:size(weights,2)
sx = vcat(weights[:,c], c==1 ? zeros(length(returns)) : reverse(weights[:,c-1]))
sy = vcat(returns, reverse(returns))
#series Shape(sx, sy)
end
end
# fake data
tickers = ["IBM", "Google", "Apple", "Intel"]
N = 10
D = length(tickers)
weights = rand(N,D)
weights ./= sum(weights, dims=2)
returns = sort!((1:N) + D*randn(N))
# plot it
portfoliocomposition(weights, returns, labels = tickers)
matplotlib has a pretty powerful polygon plotting capability, e.g. this link on plotting filled polygons:
ploting filled polygons in python
You can use this from Julia via the excellent PyPlot.jl package.
Note that the syntax for certain things changes; see the PyPlot.jl README and e.g. this set of examples.
You "just" need to calculate the coordinates from your matrix and build up a set of polygons to plot the portfolio composition graph. It would be nice to see the code if you get this working!
So I was able to draw it, and here's my code:
using PyPlot
using PyCall
#pyimport matplotlib.patches as patch
N = 10
D = 4
weights = Array(Float64, N,D)
for i in 1:N
w = rand(D)
w = w/sum(w)
weights[i,:] = w
end
weights = [zeros(Float64, N) weights]
weights = cumsum(weights,2)
returns = sort!([linspace(1,N, N);] + D*randn(N))
##########
# Plot #
##########
polygons = Array(PyObject, 4)
colors = ["red","blue","green","cyan"]
labels = ["IBM", "Google", "Apple", "Intel"]
fig, ax = subplots()
fig[:set_size_inches](5, 7)
title("Problem 2.5 part 2")
xlabel("Weights")
ylabel("Return (%)")
ax[:set_autoscale_on](false)
ax[:axis]([0,1,minimum(returns),maximum(returns)])
for i in 1:(size(weights,2)-1)
xy=[weights[:,i] returns;
reverse(weights[:,(i+1)]) reverse(returns)]
polygons[i] = matplotlib[:patches][:Polygon](xy, true, color=colors[i], label = labels[i])
ax[:add_artist](polygons[i])
end
legend(polygons, labels, bbox_to_anchor=(1.02, 1), loc=2, borderaxespad=0)
show()
# savefig("CompositionMap.png",bbox_inches="tight")
Can't say that this is the best way, to do this, but at least it is working.
I have previously asked the question "Use calibrated camera get matched points for 3D reconstruction", but the problem was not described clearly. So here I use a detail case with every step to show. Hope there is someone can help figure out where my mistake is.
At first I made 10 3D points with coordinates:
>> X = [0,0,0;
-10,0,0;
-15,0,0;
-13,3,0;
0,6,0;
-2,10,0;
-13,10,0;
0,13,0;
-4,13,0;
-8,17,0]
these points are on the same plane showing in this picture:
My next step is to use the 3D-2D projection code to get the 2D coordinates. In this step, I used the MATLAB code from caltech calibration toolbox called "project_points.m". Also I used the OpenCV C++ code to verify the result and turned out the same. (I used cvProjectPoints2())
For the 1st projection, parameters are:
>> R = [0, 0.261799387, 0.261799387]
>> T = [0, 20, 100]
>> K = [12800, 0, 1850; 0, 12770, 1700; 0 0 1]
And no distortion
>> DisCoe = [0,0,0,0]
The rotation is just two rotations with pi/12. I then got the 1st view 2D coordinates:
>> Points1 = [1850, 4254;
686.5, 3871.7;
126.3, 3687.6;
255.2, 4116.5;
1653.9, 4987.6;
1288.6, 5391.0;
37.7, 4944.1;
1426.1, 5839.6;
960.0, 5669.1;
377.3, 5977.8]
For the 2nd view, I changed:
>> R = [0, -0.261799387, -0.261799387]
>> T = [0, -20, 100]
And then got the 2nd View 2D coordinates:
>> Points2 = [1850, -854;
625.4, -585.8;
-11.3, -446.3;
348.6, -117.7;
2046.1, -110.1;
1939.0, 442.9;
588.6, 776.9;
2273.9, 754.0;
1798.1, 875.7;
1446.2, 1501.8]
THEN will be the reconstruction steps, I have already built the ideal matched points(I guess so), next step is to calculate the Fundamental Matrix, using estimateFundamentalMatrix():
>> F = [-0.000000124206906, 0.000000155821234, -0.001183448392236;
-0.000000145592802, -0.000000088749112, 0.000918286352329;
0.000872420357685, -0.000233667041696, 0.999998470240927]
with known K, I used the matlab code below to calculate essential matrix and compute the R, t, finally 3D coordinates:
E = K'*F*K;
[u1,w1,v1] = svd(E);
t = (w1(1,1)+w1(2,2))/2;
w1_new = [t,0,0;0,t,0;0,0,0];
E_new = u1*w1_new*v1';
[u2,w2,v2] = svd(E_new);
W = [0,-1,0;1,0,0;0,0,1];
S = [0,0,-1];
P1 = K*eye(3,4);
R = u2*W'*v2';
t = u2*S;
P2 = K*[R t];
for i=1:size(Points1,1)
A = [P1(3,:)*Poinst1(i,1)-P1(1,:);P1(3,:)*Points1(i,2)-P1(2,:);P2(3,:)*Points2(i,1)-P2(1,:);P2(3,:)*Points2(i,2)-P2(2,:)];
[u3,w3,v3] = svd(A);
dpt(i,:) = [v3(1,4) v3(2,4) v3(3,4)];
end
From this code I got the result as below:
>>X_result = [-0.00624167168027166 -0.0964921215725801 -0.475261364542900;
0.0348079221692933 -0.0811757557821619 -0.478479857606225;
0.0555763217997650 -0.0735028994611970 -0.480026199527202;
0.0508767193762549 -0.0886557226954657 -0.473911682320574;
0.00192300693541664 -0.121188713743347 -0.466462048338988;
0.0150597271598557 -0.133665834494933 -0.460372995991565;
0.0590515135110533 -0.115505488681438 -0.460357357303399;
0.0110271144368152 -0.148447743355975 -0.455752218710129;
0.0266380667320528 -0.141395768700202 -0.454774266762764;
0.0470113238869852 -0.148215424398514 -0.445341461836899]
With showing these points in Geomagic, the result is "a little bit bending". But there positions seemed right. I don't know why this happened. Anybody have some idea? Please see the picture:
It looks like numerical inaccuracies, maybe inside your function estimateFundamentalMatrix().
My second guess is that your estimateFundamentalMatrix() is not handling the planar case, which is a degenerate case for some algorithms (for the linear 8-points algo do not work well with planar scene for example).
The uncalibrated fundamental matrix estimation is ambiguous for planar scenes (2 solutions at least). See for example "Multiple View Geometry" by Hartley & Zisserman.
I have a tab separated XYZ file which contains 3 columns, e.g.
586231.8 2525785.4 15.11
586215.1 2525785.8 14.6
586164.7 2525941 14.58
586199.4 2525857.8 15.22
586219.8 2525731 14.6
586242.2 2525829.2 14.41
Columns 1 and 2 are the X and Y coordinates (in UTM meters) and column 3 is the associated Z value at the point X,Y; e.g. the elevation (z) at a point is given as z(x,y)
I can read in this file using dlmread() to get 3 variables in the workspace, e.g. X = 41322x1 double, but I would like to create a surface of size (m x n) using these variables. How would I go about this?
Following from the comments below, I tried using TriScatteredInterp (see commands below). I keep getting the result shown below (it appears to be getting some of my surface though):
Any ideas what is going on to cause this result? I think the problem lies with themeshgrid command, though I'm not sure where (or why). I am currently putting in the following set of commands to calculate the above figure (my X and Y columns are in meters, and I know my grid size is 8m, hence ti/tj going up in 8s):
F = TriScatteredInterp(x,y,z,'nearest');
ti = ((min(x)):8:(max(x)));
tj = ((min(y)):8:(max(y)));
[qx,qy] = meshgrid(ti,tj);
qz = F(qx,qy);
imagesc(qz) %produces the above figure^
I think you want the griddata function. See Interpolating Scattered Data in MATLAB help.
Griddata and tirscattteredinterp are extremely slow. Use the utm2deg function on the file exchange and from there a combination of both vec2mtx to make a regular grid and then imbedm to fit the data to the grid.
I.E.
for i = 1:length(X)
[Lat,Lon ] = utm2deg(Easting ,Northing ,Zone);
end
[Grid, R] = vec2mtx(Lat, Lon, gridsize);
Grid= imbedm(Lat, Lon,z, Grid, R);
Maybe you are looking for the function "ndgrid(x,y)" or "meshgrid(x,y)"