Different plots with show and savefig - python

I am plotting histograms with quite large number of bins. I am using Spyder, Python 3.6.3. The problem I found is that the figure I am seeing in iPython console is NOT the same as the saved plots. I have seen this thread which asks a similar question, however, my problem is worse, as it's not just the fonts and sizes that vary, I am actually getting different counts!
E.g. the same script:
plt.clf()
fig, ax=plt.subplots()
fig.dpi=100
plt.hist(df['POS'], bins=nbins, range=(0,dict_l[c]))
plt.savefig('current_chr17.jpg', dpi=100)
will produce this plot as a saved figure:
and show this in iPython console (interactive mode on, I'm not even asking for plt.show):
Does anyone have any explanation as to what is going on?

Related

Python Matplotlib, retain plot after command line script ends

After many hours searching I am looking for a straightforward answer to the question... "Is there ANY way to run a Python3 script from the command line, which generates a plot, and have the plot remain on-screen after the script ends"?
Ideally I would love to leave the plot running in the background, and have it remain interactive enough to allow for zooming, panning and resizing (don't care cabout updating data ... yet), but I'll settle for something as low-tech as just leaving the plot there, so I can rerun the same script with different data, so I can compare plots (ya, I know I can run the entire py script in the background if necessary, which is less elegant, but may be necessary).
Some possibilities that have some to mind that may or may not be possible: have the main script spawn a background/detached process that does the plotting; use threading; keep the script running while I want to zoom/pan/resize, then leave the plot in a static state (like a picture) when the script ends.
Tried maybe a dozen or so methods posted, but none work so far.
If it can't be done, please someone just give a short and simple answer that says so, so I can move on and kludge something together like writing an image file, and spawning a background shell that that displays a picture. Or possibly, going back to something low-tech like Bash, which will allow me to use GNUplot (yup, that works amazingly ok compared to matpltlib, so far).
Thanks to anyone who can save my sanity.
-G
Here is some of what I tried from other posts:
plt.show(block=False) will not even show a plot unless preceeded by a plt.pause(). even plt.draw() does not produce a plot. only plt.pause() before the plt.show(block=False) gives me a plot, and then the plot closes when the script ends
plt.pause(0.01) allows for zooming/resizing/etc while in a loop (which I can live with), but no way to leave (even a static plot) after the script ends. This is usable, if I can leave the plot on-screen after the script ends.
plt.draw(), plt.ion() gives anomalous results, including blank plots or no plots at all
You could just open the saved image figure, for example in this post
import sys
import subprocess
def openImage(path):
imageViewerFromCommandLine = {'linux':'xdg-open',
'win32':'explorer',
'darwin':'open'}[sys.platform]
subprocess.Popen([imageViewerFromCommandLine, path])
import matplotlib.pyplot as plt
import numpy as np
# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)
ax.set(xlabel='time (s)', ylabel='voltage (mV)',
title='About as simple as it gets, folks')
ax.grid()
fig.savefig("test.png")
openImage('test.png')
Just use background execution.

Pyplot shows image without plt.show()

I had a look at other questions on that regard, but in all other cases people had
%matplotlib inline
which caused plots to show without being prompted. I don't have it.
My plotting code looks like this:
fig, ax = plt.subplots(figsize=(17,8))
ax = plt.hist(results_df['Diff'], bins=100, density=True, histtype='step')
plt.savefig('backtester_results/figures/rf_model_lag_{n_days}_data_{lag}_lag.png',
format='png')
It's an output from testing machine learning model I'm working on and I want to put it to run for 40 hours and there will be few hundred of these plots generated in the process. So I really want them not to just get saved in a folder and not take up memory.
Do you know how to suppress this behaviour or what could be causing it?
I'm using Python 3.6 and Spyder editor. In Spyder settings I have Graphics backend set up as 'Automatic'.

Seaborn: edges in distplot don't fit the plot

When using matplotlib and seaborn in Jupyter with Python 2.7.12, I noticed that the edges of the distplot I drew don't fit the plot correctly (cf. the 2 figures below). At first I thought it was an issue with the code, but when trying the same code on someone else's laptop with the exact same versions of Jupyter and Python, the issue did not occur. Could anyone point me in the right direction?
wrong plot:
right plot:
I would gladly share the notebook with the code and the dataset, but since I am kind of new to sharing notebooks online, I do not know what the 'standard way to go' is.
Any help would be greatly appreciated.
It looks to me like the difference between the two plots is the bandwidth of the kernel used to calculate the KDE. Maybe there are different default values on both machines.
Try to play with either the bw= or kernel= parameters (documentation). Like so:
fig,(ax1,ax2) = plt.subplots(2,1, figsize=(5,10))
x = np.random.randn(100)
sns.distplot(x, ax=ax1)
sns.distplot(x, kde_kws={'bw':5}, ax=ax2)

Matplotlib Graph not showing up on OSX?

I am currently trying to graph data using Python3 and matplotlib. I am developing on OSx Sierra and when I run, it is not showing up. There are no errors returned. I included plt.show() in my code and it is definitely running. Any help to get this graph showing would be appreciated. Vanilla Python3, edited in Emacs, ran from both IDLE and terminal. Neither work. Thank you.
import matplotlib.pyplot as plt
plt.show()
Does not produce anything, and there are no errors. I have tried
plt.switch_backend('MacOSX') and the error persists.
Just to wrap up the comments into an answer: pyplot.show() only produces a figure, if a figure has been created. This can be done explicitly by stating
fig = plt.figure()
or implicitly by plotting something (the figure is then created in the background), e.g.
plt.plot([1,2,3])
once plt.show() is called, all currently active figures will be displayed on the screen.

matplotlib does not show plot()

I tried running plt.show() but no plot is shown. I had tried lots of solutions from stackoverflow including setting matplotlib backend to Qt4Agg, switching to other backends (i.e. TkAgg, Agg) and reinstalling matplotlib package but still not solving the issue. Some solutions that I had tried but not working are:
matplotlib does not show my drawings although I call pyplot.show()
Matplotlib.Pyplot does not show output; No Error
Why matplotlib does not plot?
Matplotlib does not show labels or numbers
Below is the code that I tried to run:
plt.scatter(pf["age"], pf["friend_count"])
plt.xlabel = "age"
plt.ylabel = "friends count"
plt.title = "Facebook Friends count by Age"
plt.show()
When plt.scatter(pf["age"], pf["friend_count"]) code was run, a scatter plot was shown but with no labels and title. Running plt.show() did not plot and no error was shown. Appreciate any help.
I installed Anaconda with Python 3 for Windows OS. My Mac laptop is running on Bootcamp.
The labels must use parentheses such as plt.xlabel("text"), not assigned to a string with = like you have in your example code. Make the changes in your code, save the changes, quit and reopen Spyder or whatever interpreter you are running, then run the code again.
plt.figure(1)
plt.scatter(pf["age"], pf["friend_count"])
plt.xlabel("age")
plt.ylabel("friends count")
plt.title("Facebook Friends count by Age")
plt.show()

Categories