In jupyter notebook, with %matplotlib inline enabled, the output of a cell that both prints text and plots a figure will have the entirety of the text appear before the figure is shown. This happens even if the figure was generated (and called show() on) before the text was printed.
For example:
fig = plt.figure()
fig.add_subplot(111)
fig.show()
print "hello"
will show the 'hello' before the empty figure.
How do I fix this so that each figure appears truly inline?
I think you want to explicitly display the figure, using IPython's display function:
from IPython.display import display
fig = plt.figure()
fig.add_subplot(111)
display(fig)
print("hello")
Related
If I execute following code:
figure
t=0:.1:10;
dummy=plotyy(t,sin(t),t,2*cos(t));
set(dummy(1),'ylim',[-1 1]);
set(dummy(2),'ylim',2*[-1 1]);
axes(dummy(1)); xlabel('xlabel'); ylabel('ylabel');
axes(dummy(2)); ylabel('ylabel2');
dummy(1).YTick=[-1:.5:1];
dummy(2).YTick=[-2:1:2];
legend(dummy(1),'Legend1','Location','NorthWest')
legend(dummy(2),'Legend2','Location','NorthEast')
I obtain following figure:
It seems that the default colour of the right-hand legend is grey instead of white. Which command do I need to enter in order to make it white?
It is a good question, I can only assume that MATLAB try's to match some colors for readability or something like that. If you want to know it exactly, maybe MATLAB provides a legend.m-file within the program directory which you could open to have a look at the specific source.
In case you only want to know how to work around it to make both legends white, use this code:
l1 = legend(...);
l2 = legend(...);
set(l2, 'color' 'white');
I've plotted data points and fitted an exponential curve between them using 'fit' in Matlab. The problem is that with the fit-function I got the fitted line I wanted to plot, but also extra markers on top of my regular markers. I solved this problem by plotting the wanted markers on top of the unwanted so that they couldn't be seen. Now to the problem. When I want to show the legends those dots are also in there. How can I remove the markers from the legend without removing the fitted line since both of them are hidden inside the fit-function? Can I stop 'fit' from plotting the unwanted markers? So, I want to remove the blue dot called 'hoff' in the picture below.
You can leave out legend-entries by manually leaving out the handles of the lines, that you dont want to be in the legend. Try this:
%if you plot something, that you want showing up in the legend, save its handle:
h_line = plot(x,y)
%you dont want to show up this line? dont do anything, just plot it:
plot(myMarker)
%then set the legend-> you can add the text for your legend-entries with
%a cell-array containing the strings you want to show up:
legend([h_line another_line],{'Text1' 'Text2'})
with the example (see comments) I came to this solution:
close all
X=[1:10];
Y=X*0.5+0.1;
ft = fittype('poly2');
f = fit(X', Y',ft);
ha=plot(f)
hold on
hc=plot(X,Y)
hb=errorbar(X, Y, X*0.1, 'squarek','MarkerFaceColor','k','markersize',5)
hleg1 = legend([ha hc],{'hnh','ghg'});
-> this is just about splitting the plot-command. Hope that helps...
the result should look like this:
I'm having some matlab plots. when I save the plot and then put it in my word document and then save it as pdf file. I get the plot labels blurry and some letters is unclear ?!
plot(d1,S,'*');
title('Frequency','FontWeight','bold','FontSize',11);
xlabel('delta','FontWeight','bold','FontSize',11), ylabel('sigma','FontWeight','bold','FontSize',11);
why does that happened (got angry)?!
how can I fix it ?!
There are many discussions about this on the web, but non of the solutions actually satisfied me when I wanted to export a graph to an image.
Anyway here is what I've done:
MyFont = {'FontName', 'Times New Roman', 'FontSize', 25};
graph_size = [1200 800]; % in pixels
fig_h = figure('Units', 'pixels', 'Position', [10 50 graph_size]);
% Do your plot
x = 0:0.1:2*pi;
plot(x, sin(x))
set(gca, MyFont{:}); % Adjust all the font sizes in the axes
Now you can copy a vector-based version (which is nicest quality as #wakjah mentioned) to clipboard with print (as #Amro said):
print -dmeta
Or with hgexport which exports to metafile again:
hgexport(figH,'-clipboard')
However you need to adjust the graph_size and FontSize in MyFont manually to get your desired output. But the good thing is that if you want it for some publication you just need to do it once.
Please note that although you are exporting the graphs as a vector-based format but your graph lines would still seem fractured if you zoom on them but they are not blurry. This is why you might want to increase the size of your graph on screen (graph_size and consequently the FontSize) to have a more accurate graph.
Hope this helps.
Related posts:
MATLAB: print a figure to pdf as the figure shown in the MATLAB
In matlab, how do you save a figure as an image in the same way as using "Save As..." in the figure window?
I want to add a x-axis line at 0 to a Matlab figure so that I can compare my data to see if it is positive or negative when saving the figures to a jpg. What is the best way to do this? I know you can use line() but it just seems cumbersome because you need to specify the x and the y ranges. Is there an easier way?
There exist an undocumented function graph2d.constantline:
plot(-2:5, (-2:5).^2-1)
%# vertical line
hx = graph2d.constantline(0, 'LineStyle',':', 'Color',[.7 .7 .7]);
changedependvar(hx,'x');
%# horizontal line
hy = graph2d.constantline(0, 'Color',[.7 .7 .7]);
changedependvar(hy,'y');
The nice thing is that it internally implements a listener for the axes limits (handles change like pan, zoom, etc..). So the lines would appear to extend to infinity.
You could get this x range directly after the figure has been created. It goes a little something like this:
x=-2:5;
y=x.^2-1;
figure()
plot(x,y);
xlim = get(gca,'xlim'); %Get x range
hold on
plot([xlim(1) xlim(2)],[0 0],'k')
Note that if you do any manual zooming out in the figure, the line might have to be redrawn to go over the entire new x range.
I don't believe there is a built-in way that is more convenient. I use hline() and vline() from FileExchange, which work like a charm:
http://www.mathworks.com/matlabcentral/fileexchange/1039
A vline and hline command like in GNU R would be great, but I could not find a shorter solution than
plot(1:10,sin(1:10));
line(xlim,[0 0],'Color','r')
Draw your data by plot() command or stem(). A figure window will open.
Then on the figure window, click on the [insert] command from the
menu bar, a drop-down menu will appear.
From this menu click on the [line] command, now the shape of the
cursor will change into a plus sign.
Now you can draw a line anywhere you want, either horizontal or
vertical or slanted.
You can change the properties of line by right clicking on the
line, a menu will appear from which you can choose your desires
properties.
If you want to have some ticks on the line then you can use add
text option, and place text where ever you want.
If you would like to have a code for your figure, click on [file]
menu and then click on [generatecode] option, a new text editor
window will open, you can save this code for further use. Good luck.
Since MATLAB R2018b there is yline for this purpose:
yline(0)
draws a horizontal line at y==0.
How do you plot two figures at the same time in Matlab? Every time I use surf() it plots over the old one. Also, how do you save the images so you can export them to MS word or powerpoint or something?
You can plot two figures in separate windows:
figure(1)
% do plotting
figure(2)
% do plotting
or in subplots:
figure(1)
subplot(1, 2, 1)
% do plotting
subplot(1, 2, 2)
% do plotting
For more info, you can see the MATLAB docs for the figure and subplot functions (in the help menu).
For printing the images to a file, see the documentation for the print function. Or just go to File -> Save As, and pick the image type you want.
Use the command figure before each plot/surf/mesh.
example
X = [1:5];
figure('Name', 'My plot');
plot(X, X+X);
figure('Name', 'My plot number 2');
plot(X, X + X + X);
Call figure before calling surf. figure opens a new figure window. When you call surf, it will plot into the currently selected figure.
You can copy-paste figures into Word or Powerpoint by using, in the figure window, the menu Edit->Copy Figure. If in, say Word, you click on the pasted figure and select 'ungroup', you can even go and edit the figure.
To save, you select 'Save as...' in the File-menu in the figure window. For Adobe Illustrator, save as .eps (works better than .ai).
As another small addition to previous responses, you can print a figure directly to clipboard using print -dmeta command. Then just paste to Word or PowerPoint document. I found it very neat.
#kwatford If you use hold all rather than hold on then Matlab will use the next defined colour and linestyle for that plot. check out the difference between
figure(1);
plot(rand(100,1));
hold on ;
plot(rand(100,1)+2);
and
figure(2);
plot(rand(100,1));
hold all;
plot(rand(100,1)+2);
To create a new figure in a separate window, just say figure. To export as an image file, use the print command with the appropriate -d option to select the file format. Like so:
figure;
plot(rand(100,1), rand(100, 1), 'r*');
print -dpng 'MyImage.png'
Execute hold on to hold the current figure. New plots will be added to the existing plots. Use hold off to change it back to the previous behavior.
In addition to the print command (see Drew Hall's response), you can export to other formats via the File menu, or use the Copy Figure function of the edit menu. If you want to paste it into Word or Powerpoint, you might get a better result if you use "Paste Special" instead of normal Paste.