Adding column values to octave bar diagram - plot

I'm making new bar diagram in my OCTAVE application. Because of the better readings I want to add actual values for each bar. The actual values of each bar column should be located on the high Y=50% and centrally centered with each bar column. I have search over the google, but I didnt found any real example of values over the bar columns.
My example made in paint, how should look:
Picture above is a example how should look - for example purposes there are RED colored values of the each bar column.
Code of the plotting of this bar diagram:
subplot(5, 1, 5);
y2 = [data1; data2; data3; data4];
x = [1 ,2 ,3, 4];
labels = ["DATANAME1"; "DATANAME2"; "DATANAME3"; "DATANAME4"];
bar (x, y2, 0.5, 'facecolor', [0, 0.5, 1]);
set(gca, 'xticklabel', labels);
title("Something [%]");
xlabel('XLABEL');
ylabel("%");

You can use the text command for putting any text on/over any plot.
Here's my suggestion, I slightly re-worked your code:
% Data
x = [1, 2, 3, 4];
y2 = [2; 52; 3; 43];
% Original plot
bar(x, y2, 0.5, 'FaceColor', [0, 0.5, 1]);
labels = ['DATANAME1'; 'DATANAME2'; 'DATANAME3'; 'DATANAME4'];
set(gca, 'XTickLabel', labels);
title('Something [%]');
xlabel('XLABEL');
ylabel('%');
% Additional plot
y = max(y2) / 2; % "located on the high Y=50%"
values = [num2str(y2) repelem(' %', 4, 1)];
text( x - 0.1, ... % x values to put text (some negative displacement for "centrally centered with each bar column")
repelem(y, 4, 1), ... % y values to put text (four times y)
values, ... % Actual values as text plus "%" to put
'Color', 'r', ... % Red text
'FontWeight', 'bold'); % Bold text
The output then looks like this:
I used Octave 5.1.0, the repelem command might not be available before Octave 5.x, but there are alternatives to achieve what repelem does.
Notice, the construction of values (only) works, because y2 is a column vector. Otherwise, adding the "%" to each value in y2 might be a bit more complicated.
Hope that helps!

Related

How to animate 3D scatter plot by adding each point at a time in R or MATLAB

I have a set of 3D coordinates here. The data has 52170 rows and 4 columns. Each row represent one point. The first column is point index number, increasing from 1 to 52170. The second to fourth columns are coordinates for x, y, and z axis, respectively. The first 10 lines are as follow:
seq x y z
1 7.126616 -102.927567 19.692112
2 -10.546907 -143.824966 50.77417
3 7.189214 -107.792068 18.758278
4 7.148852 -101.784027 19.905006
5 -14.65788 -146.294952 49.899158
6 -37.315742 -116.941185 12.316169
7 8.023512 -103.477882 19.081482
8 -14.641933 -145.100098 50.182739
9 -14.571636 -141.386322 50.547684
10 -15.691803 -145.66481 49.946281
I want to create a 3D scatter plot in which each point is added sequentially to this plot using R or MATLAB. The point represented by the first line is added first, then the point represented by the second line, ..., all the way to the last point.
In addition, I wish to control the speed at which points are added.
For 2D scatter plot, I could use the following code:
library(gganimate)
x <- rnorm(50, 5, 1)
y <- 7*x +rnorm(50, 4, 4)
ind <- 1:50
data <- data.frame(x, y, ind)
ggplot(data, aes(x, y)) + geom_point(aes(group = seq_along(x))) + transition_reveal(ind)
But I cannnot find information on how to do this for 3D scatter plot. Can anyone show me how this could be done? Thank you.
This is an answer for MATLAB
In a general fashion, animating a plot (or 3d plot, or scatter plot, or surface, or other graphic objects) can be done following the same approach:
Do the first plot/plot3/scatter/surf, and retrieve its handle. The first plot can incorporate the first "initial" sets of points or even be empty (use NaN value to create a plot with invisible data point).
Set axis limits and all other visualisation options which are going to be fixed (view point, camera angle, lightning...). No need to set the options which are going to evolove during the animation.
In a loop, update the minimum set of plot object properties: XData, YData ( ZData if 3D plot, CData if the plot object has some and you want to animate the color).
The code below is an implementation of the approach above adapted to your case:
%% Read data and place coordinates in named variables
csvfile = '3D scatter plot.csv' ;
data = csvread(csvfile,2) ;
% [optional], just to simplify notations further down
x = data(:,2) ;
y = data(:,3) ;
z = data(:,4) ;
%% Generate empty [plot3] objects
figure
% create an "axes" object, and retrieve the handle "hax"
hax = axes ;
% create 2 empty 3D point plots:
% [hp_new] will contains only one point (the new point added to the graph)
% [hp_trail] will contains all the points displayed so far
hp_trail = plot3(NaN,NaN,NaN,'.b','Parent',hax,'MarkerSize',2) ;
hold on
hp_new = plot3(NaN,NaN,NaN,'or','Parent',hax,'MarkerSize',6,'MarkerEdgeColor','r','MarkerFaceColor','g','LineWidth',2) ;
hold off
%% Set axes limits (to limit "wobbling" during animation)
xl = [min(x) max(x)] ;
yl = [min(y) max(y)] ;
zl = [min(z) max(z)] ;
set(hax, 'XLim',xl,'YLim',yl,'ZLim',zl)
view(145,72) % set a view perspective (optional)
%% Animate
np = size(data,1) ;
for ip=1:np
% update the "new point" graphic object
set( hp_new , 'XData',x(ip), 'YData',y(ip), 'ZData',z(ip) )
% update the "point history" graphic object
% we will display points from index 1 up to the current index ip
% (minus one) because the current index point is already displayed in
% the other plot object
indices2display = 1:ip-1 ;
set(hp_trail ,...
'XData',x(indices2display), ...
'YData',y(indices2display), ...
'ZData',z(indices2display) )
% force graphic refresh
drawnow
% Set the "speed"
% actually the max speed is given by your harware, so we'll just set a
% short pause in case you want to slow it down
pause(0.01) % <= comment this line if you want max speed
end
This will produce:

How to create exponential graph

How can I make an x-axis that doubles for every increment? I want equal distances between 0, 128, 256, 512, 1024 and 2048. How can I do that?
I'm trying to plot points from a benchmark where I measured time and doubled the memory size every increment.
You can cheat and plot with a linear axis, like from 1 up to as many numbers as you desire, then change the labels when you're done. You can use the 'xtick' property to set what horizontal tick values on your graph remain and the 'xticklabel' property to change the labels to your desired values.
labels = [0 128 256 512 1024 2048]; % Provide your labels here
x = 1 : numel(labels);
y = rand(1, numel(x)); % Insert your data here
plot(x, y, 'b.'); % Plot your data
set(gca, 'xtick', x); % Change the x-axis so only the right amount of ticks remain
set(gca, 'xticklabel', labels) % Change the labels to the desired ones
I get the following graph. Note that the data I'm plotting is completely random as I don't have your data but I want to demonstrate what the changed plot looks like:
For more properties that you can change on your graph, see the Axes Properties page on the Octave docs.
With apologies to Rayryeng, since I'm essentially proposing the same method at heart, but I felt it was missing important info, such as how to convert the axis itself to equally spaced intervals in the first place, without messing with the data. So here's a complete solution for example data X vs Y, producing the equivalent of semilogx for base 2.
Y = 1 : 10;
X = 2 .^ Y;
XTicks = log2(X);
XTickLabels = {};
for XTick = XTicks
XTickLabels{end+1} = sprintf('2^{%d}', XTick);
end
plot (log2 (X), Y);
set(gca, 'xtick', XTicks, 'xticklabel', XTickLabels);
Note that if you plan to 'superimpose' another plot on top of this, you'll have to take into account that the actual values in the X axis are essentially "1, 2, 3, ... 10", so either "log-ify" the new plot's X-axis values too, before superimposing via hold on, or plot onto another, independent set of axes entirely and place them in the same position.
Note: I have assumed that you're after a base-2 logarithmic x-axis. If you do actually want the 0-128 interval to be the same as the 128-256 interval, then modify as per Rayrengs answer --- or even better, use a more appropriate graph, like a bar graph! (i.e. with the 'powers-of-two' used purely as descriptive labels for each column)

Using scatterplot3d to plot a sphere

I have a matrix of the x,y,z coordinates of all amino acids. I plot the protein in 3D space using the following function:
make.Plot <- function(position.matrix, center, radius){
scatterplot3d(x = position.matrix[,4], y = position.matrix[,5], z = position.matrix[,6], type = 'o', color = 'blue')
}
Each row in the position.matrix is for a different amino acid. What I would like to do is modify the function so if I pass it a "center" which would correspond to a number in column 2 of position matrix (which lists the amino acid numberings), as well as a radius, I want a sphere with center at that amino acid.
For instance, if I pass it (position.matrix, 9, 3), I want it to plot a sphere of radius 3 around amino acid 9. I have uploaded a copy of the position data here:
http://temp-share.com/show/YgFHv2J7y
Notice that the row count is not always the canonical count as some residues are skipped. I will always pass it the "canonical" count...
Thanks for your help!
Here is a tested modification of your code. It adds a length-2 size vector for cex.symbols which is chosen by adding 1 to a logical vector:
make.Plot <- function(position.matrix, center, radius){
scatterplot3d(x = position.matrix[,4], y = position.matrix[,5],
z = position.matrix[,6], type = 'o',
cex.symbols=c(1,radius)[1+(position.matrix[,2]==center)], color = 'blue')
}
I wonder if what you really want is the rgl package. It has shapes and an interactive plotting environment. With scatterplot3d you could make the chose point red with this code:
myplot <- make.Plot(position.matrix, 3, 9)
myplot$points3d(position.matrix[3 , 4:6], col="red", cex=10)
I also located some code to draw a "parametric sphere" which can be adapted to creating a highlighting indicator:
myplot <- make.Plot(position.matrix, 3, 9)
a=seq(-pi,pi, length=10);
myplot$points3d(x=2*c(rep(1, 10) %*% t(cos(a)))+position.matrix[3 , 4] ,
y=2*c(cos(a) %*% t(sin(a)))+position.matrix[3 , 5],
z=2*c(sin(a) %*% t(sin(a)))+position.matrix[3 , 6],
col="red", cex=.2)

How can I add markers to implicit_plot?

The plot is generated by the following commands in Maxima. How can I add dots / markers at given coordinates?
load(implicit_plot);
ip_grid_in:[15,15]$
implicit_plot ([x^2 = y^3 - 3*y + 1, y=x^2], [x, -4, 4], [y, -4, 4],
[gnuplot_preamble, "set zeroaxis"]);
I have tried adding [discrete, [[1.0,1.0], [1.0, 2.0]]] to the list of equations but apperantly implicit_plot cannot handle it (perhaps because it is not an equation).
I'm no maxima wizard, but in gnuplot, I would add points using set label.
set label 1 at 1,1 point
set label 2 at 1,2 point
Based on what you have above, I would think you could just add this to the preamble:
implicit_plot ([x^2 = y^3 - 3*y + 1, y=x^2], [x, -4, 4], [y, -4, 4],
[gnuplot_preamble, "set zeroaxis;set label 1 at 1,1 point;set label 2 at 1,2 point"]);
It's a bit ugly, but I'm betting that it works :)
Of course, you may need to unset those labels in a later preamble if maxima re-uses the same gnuplot instance and doesn't issue a reset implicitly:
unset label 1; unset label 2
There are lots of things you can do to customize the appearance of the points (color, point-type, etc). in gnuplot, help label should discuss a bunch of those options if you're interested.

How to specify the margin of a plot in mm/cm using matplotlib?

Example
Suppose I have two triangles:
A triangle with points (0, 0), (10, 0), (10, 0.5) and
a triangle with points (0, 0), (1, 0), (0.5, 11)
The resulting two plots without specifying the xlim and ylimlook like this:
Question
What do I need to do to satisfy all points listed below?
Make the triangle visible, so that no line of the triangle is hidden by an axis
Specify the same margin for all plots in mm, cm or other unit.
(in the example above only two triangles were used. Actually I have n triangles.)
As margin I mean the distance between the outer points of the triangle and the axis.
The resulting plots should look like this
with the difference that the distances, which are marked with the red arrows, should all be the same!
I don't know of a way to to it in cm/mm, but you can do it with the precentage of the total size:
# you don't really need this see bellow
#from matplotlib.backends.backend_pdf import PdfPages
import pylab
import matplotlib.pyplot as plt
left,bottom,width,height = 0.2,0.1,0.6,0.6 # margins as % of canvas size
fig = plt.figure(figsize=(4,4),facecolor="yellow") # figure size in Inches
fig.patch.set_alpha(0.8) # just a trick so you can see the difference
# between the "canvas" and the axes
ax1 = plt.Axes(fig,[left,bottom,width,height])
ax1.plot([1,2,3,4],'b') # plot on the first axes you created
fig.add_axes(ax1)
ax1.plot([0,1,1,0,0], [0,0,1,1,0],"ro") # plot on the first axes you created
ax1.set_xlim([-1.1,2])
ax1.set_ylim([-1.1,2])
# pylab.plot([0,1,1,0,0], [0,0,1,1,0],"ro") avoid usig if you
# want to control more frames in a plot
# see my answer here
#http://stackoverflow.com/questions/8176458/\
#remove-top-and-right-axis-in-matplotlib-after-\
#increasing-margins/8180844#8180844
# pdf = PdfPages("Test.pdf")# you don't really need this
# pylab.savefig(pdf, papertype = "a4", format = "pdf")
# automagically make your pdf like this
pylab.savefig("Test1.pdf", papertype="a4",facecolor='y')
pylab.show()
pylab.close()
# pdf.close()
and the output is:
corrected image:
Your two triangles with points (0, 0), (10, 0), (10, 0.5) and (0, 0), (1, 0), (0.5, 11) would be represented in pylab as:
Ax = [0, 10, 10]
Ay = [0, 0, 0.5]
Bx = [0, 1, 0.5]
By = [0, 0, 11]
pylab.plot(Ax, Ay)
pylab.plot(Bx, By)
Let's see what the lowest X value is:
lowestX = None
for x in Ax+Bx:
if lowestX==None or x<lowestX:
lowestX = x
Exercise for the reader to do the same for highestX, lowestY, and highestY.
Now, consider a boundary of 2 units, you can add / subtract these units from the lowest and highest values and set xlim and ylim:
margin = 2
pylab.xlim([lowestX-margin, highestX+margin])
pylab.ylim([lowestY-margin, highestY+margin])

Resources