Result image not showing in VSCode - python

Im trying to visualize the data using python in VSCode, the code is down below
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
train_df = pd.read_csv('D:/GBM project/train_labels.csv')
plt.figure(figsize = (5, 5))
sns.countplot(data = train_df, x = 'MGMT_value')
This code run successfully but no image is shown, could someone tells me where's the problem?
Thanks in advance!

Maybe it's closing after running successfully. If you're not getting any exceptions after code execution, try following things
add temp=input() at the end of the program
add plt.show() at the end of the program
add sns.set_theme() before last line

Related

How do I render Python plots in RMarkdown?

For the life of me, I can't get to render plots in RMarkdown using Python. The plots display in my Python Editor, but not when I switch to RStudio trying to build a PDF/HTML report. I've been all over the internet, everyone has an answer, but none has the solution to my issue. Here's the error message I get the attached error below:
Below I made up some data to show what I'm trying to achieve. Once the application hits the seaborn line it produces the attached error message in RStudio
knitr::opts_chunk$set(echo = TRUE)
library(reticulate)
Importing Required Packages
import pandas as pd
import numpy as np
from scipy.stats import uniform # for training-and-test split
import statsmodels.api as sm # statistical models (including regression)
import statsmodels.formula.api as smf # R-like model specification
import matplotlib.pyplot as plt # 2D plotting
import seaborn as sns
x = np.random.normal(0, 1, 20)
y = np.random.normal(0, 2, 20)
sns.scatterplot(x, y)
I found the answer here
All I needed was to add these two lines in the R setup chunk below the library(reticulate) call
matplotlib <- import("matplotlib")
matplotlib$use("Agg", force = TRUE)

Seaborn Plot is not displaying

I have been trying to plot a simple bar chart using Seaborn. Oddly enough the previous plots worked, but these ones do not appear. No error is being thrown and as far as I can tell the code is okay. Perhaps a more experienced eye will be able to find an error.
import pandas as pd
import numpy as np
import pyodbc
import matplotlib.pyplot as plt
import seaborn as sns
region_pct_25 = region_totals.iloc[0:6, :]
region_pct_25['Opp_Lives_pct'] = ((region_pct_25.Lives / region_pct_25.Lives.sum())*100).round(2)
region_pct_25.reset_index(level=['RegionName'], inplace=True)
region_25_plt = sns.barplot(x="RegionName", y="Opp_Lives_pct", data=region_pct_25, color = 'g').set_title("Client Usage by Region: ADD ")
plt.show()
No plot is showing. Please help wherever you can!
adding %matplotlib inline to the preamble resolved the issue!

Unable to use seaborn plotting features in Visual Studio

I've written code to read in certain data from a CSV file, perform a PCA analysis on the data with the sklearn library, and then plot the resulting data as a heatmap. The code doesn't show any errors when run, but it also outputs no graph and just a line saying AxesSubplot(0.125,0.11;0.62x0.77).
I'm wondering if Visual Studio is unable to display plots like this and if so what would be a better IDE for me to use for this project. If not can anyone see a problem that would prevent this code from displaying a heatmap? Copying the relevant code below
import os
import matplotlib as mpl
if os.environ.get('DISPLAY','') == '':
print('no display found. Using non-interactive Agg backend')
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
sns.set()
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import pandas as pd
# Scaling the data for PCA
scaler = StandardScaler()
x = StandardScaler().fit_transform(data)
pca = PCA(n_components = 2)
pca.fit(x)
finSet = pca.transform(x)
hm = sns.heatmap(finSet)
plt.show()
You may delete the lines
if os.environ.get('DISPLAY','') == '':
print('no display found. Using non-interactive Agg backend')
mpl.use('Agg')
Those lines are intendet to query if the code is run in an environment which has a display. If no display is there, it should not try to create a plotting window on screen.
However, even if you have a display, but os.environ does not have a "DISPLAY" key, the code will falsely assume that no plotting window shall be created. This seems to be the case on Windows at least.
You might also want to inform the source of this code about their error.

Python plt: close or clear figure does not work

I generate a lots of figures with a script which I do not display but store to harddrive. After a while I get the message
/usr/lib/pymodules/python2.7/matplotlib/pyplot.py:412: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (matplotlib.pyplot.figure) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam figure.max_num_figures).
max_open_warning, RuntimeWarning)
Thus, I tried to close or clear the figures after storing. So far, I tried all of the followings but no one works. I still get the message from above.
plt.figure().clf()
plt.figure().clear()
plt.clf()
plt.close()
plt.close('all')
plt.close(plt.figure())
And furthermore I tried to restrict the number of open figures by
plt.rcParams.update({'figure.max_num_figures':1})
Here follows a piece of sample code that behaves like described above. I added the different options I tried as comments at the places I tried them.
from pandas import DataFrame
from numpy import random
df = DataFrame(random.randint(0,10,40))
import matplotlib.pyplot as plt
plt.ioff()
#plt.rcParams.update({'figure.max_num_figures':1})
for i in range(0,30):
fig, ax = plt.subplots()
ax.hist([df])
plt.savefig("/home/userXYZ/Development/pic_test.png")
#plt.figure().clf()
#plt.figure().clear()
#plt.clf()
#plt.close() # results in an error
#plt.close('all') # also error
#plt.close(plt.figure()) # also error
To be complete, that is the error I get when using plt.close:
can't invoke "event" command: application has been destroyed
while executing "event generate $w <>"
(procedure "ttk::ThemeChanged" line 6)
invoked from within "ttk::ThemeChanged"
The correct way to close your figures would be to use plt.close(fig), as can be seen in the below edit of the code you originally posted.
from pandas import DataFrame
from numpy import random
df = DataFrame(random.randint(0,10,40))
import matplotlib.pyplot as plt
plt.ioff()
for i in range(0,30):
fig, ax = plt.subplots()
ax.hist(df)
name = 'fig'+str(i)+'.png' # Note that the name should change dynamically
plt.savefig(name)
plt.close(fig) # <-- use this line
The error that you describe at the end of your question suggests to me that your problem is not with matplotlib, but rather with another part of your code (such as ttk).
plt.show() is a blocking function, so in the above code, plt.close() will not execute until the fig windows are closed.
You can use plt.ion() at the beginning of your code to make it non-blocking. Even though this has some other implications the fig will be closed.
I was still having the same issue on Python 3.9.7, matplotlib 3.5.1, and VS Code (the issue that no combination of plt.close() closes the figure). I have three loops which the most inner loop plots more than 20 figures. The solution that is working for me is using agg as backend and del someFig after plt.close(someFig). Subsequently, the order of code would be something like:
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
someFig = plt.figure()
.
.
.
someFig.savefig('OUTPUT_PATH')
plt.close(someFig) # --> (Note 1)
del someFig
.
.
.
NOTE 1: If this line is removed, the output figures may not be plotted correctly! Especially when the number of elements to be rendered in the figure is high.
NOTE 2: I don't know whether this solution could backfire or not, but at least it is working and not hugging RAM or preventing plotting figures!
import tensorflow as tf
from matplotlib import pyplot as plt
sample_image = tf.io.read_file(str(PATH / 'Path to your file'))
sample_image = tf.io.decode_jpeg(sample_image)
print(sample_image.shape)
plt.figure("1 - Sample Image ")
plt.title(label="Sample Image", fontsize=12, color="red")
plt.imshow(sample_image)
plt.show(block=False)
plt.pause(3)
plt.close()
plt.show(block=False)
plt.pause(interval) do the trick
This does not really solve my problem, but it is a work-around to handle the high memory consumption I faced and I do not get any of the error messages as before:
from pandas import DataFrame
from numpy import random
df = DataFrame(random.randint(0,10,40))
import matplotlib.pyplot as plt
plt.ioff()
for i in range(0,30):
plt.close('all')
fig, ax = plt.subplots()
ax.hist([df])
plt.savefig("/home/userXYZ/Development/pic_test.png")

Python pandas : pd.options.display.mpl_style = 'default' causes graph crash

Everything is in the title. My graph is displayed properly when I do not set this option at the beginning of my python script, otherwise it opens the window for the graph but closes it straightback and end the run.
I am using pandas 0.14.0 and matplotlib 1.3.0.
Anyone already saw this ? You can see my code below if needed.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#pd.options.display.mpl_style = 'default'
df = pd.DataFrame(np.random.randn(1000, 4), index=pd.date_range('1/1/2000',periods=1000), columns=list('ABCD'))
df = df.cumsum()
df.plot(legend=False)
plt.show()
I was experiencing a similar error with Matplotlib v1.4. The solution I found is to use
matplotlib.style.use('ggplot')
rather than
pd.options.display.mpl_style = 'default'
See - https://pandas-docs.github.io/pandas-docs-travis/visualization.html
Use the following:
plt.show(block=True)

Categories

Resources