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.
Related
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)
#%%
from Utils.ConfigProvider import ConfigProvider
import os
import cv2
import numpy as np
from matplotlib import pyplot as plt
config = ConfigProvider.config()
and
#%%
inspected = cv2.imread(config.data.inspected_image_path, 0)
reference = cv2.imread(config.data.reference_image_path, 0)
diff = np.abs(inspected - reference)
plt.figure()
plt.title('inspected')
plt.imshow(inspected)
plt.show()
note config.data.inspected_image_path and config.data.reference_image_path are valid paths.
No errors appear, but no images are shown as well.
Running the same code from a python file does show the image.
I have something missing from the notebook.
This happens both when running using jupyter notebook and directly from PyCharm (pro)
How do I get to see images? all other answers I found just tell me to plt.show() but this obviously does not work.
I don't mind a cv2 solution as well.
You need to set a matplotlib backend.
You can do this with
%matplotlib inline
If you want to be able to interact with the plot, use
%matplotlib notebook
I work with matplotlib. When I add the following lines, the figure is not displayed.
import matplotlib
matplotlib.use('Agg')
here is my code :
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plot
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
fig = plot.figure(figsize=(12,9))
def convert_sin_cos(x):
fft_axes = fig.add_subplot(331)
y = np.cos(x)
fft_axes.plot(x,y,'g*')
for i in range(3):
fft_axes = fig.add_subplot(332)
x=np.linspace(0,10,100)
fft_axes.plot(x,i*np.sin(x),'r+')
plot.pause(0.1)
convert_sin_cos(x)
Thanks
That's the idea!
When I run your code, the console says:
matplotlibAgg.py:15: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
How can it be useful? When you're running matplotlib code in a terminal with no windowing system, for example: a cluster (running the same code with different inputs, getting lot of results and without the need to move the data I can plot whatever I need).
I wrote this code. It should display the plots in spyder ide.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error
import scipy.signal
import scipy.stats
from sklearn.model_selection import train_test_split
train = pd.read_csv("train.csv", nrows=9000000,dtype={'acoustic_data':np.int16,'time_to_failure':np.float64})
train.rename({"acoustic_data": "signal", "time_to_failure": "quaketime"}, axis="columns", inplace=True)
#visualization(train,title="Acoustic data and time to failure: sampled data")
fig, ax = plt.subplots(2,1, figsize=(20,12))
ax[0].plot(train.index.values, train.quaketime.values, c="darkred")
ax[0].set_title("Quaketime of 10 Mio rows")
ax[0].set_xlabel("Index")
ax[0].set_ylabel("Quaketime in ms")
ax[1].plot(train.index.values, train.signal.values, c="mediumseagreen")
ax[1].set_title("Signal of 10 Mio rows")
ax[1].set_xlabel("Index")
ax[1].set_ylabel("Acoustic Signal")
Spyder IDE dispaly following message instead of plot
Figures now render in the Plots pane by default. To make them also
appear inline in the Console, uncheck "Mute Inline Plotting" under the
Plots pane options menu.
I have tested this code in google colab. It plots the required graph. How I can plot in Spyder IDE.
I am using Spyder 4.0.1. I did not found any "Mute Inline Plotting" option to uncheck
What you have is neither an error nor a warning. It's an instruction. You can find the options following:
Ignore the console outputs, that's just to give you orientation in Spyder 4.0.1.
I am trying to use the 3D scatter plot object in python. And I have successfully done this on my laptop. However, I can not copy and paste code onto my desktop. When I do this I get an error. I will attach my the section of my code below that is giving me trouble. I am using Anaconda to run my code. I will note that my laptop uses python 3.6 and my desktop uses 3.7, but I do not think that is causing it. The error I is get is as follows. "ValueError: Unknown projection '3d'"
import numpy as np
from scipy import optimize
import time
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import preprocessing
from sklearn.svm import SVR
import multiprocessing as mp
from obj_class import objective_class
import pdb
import scipy.integrate as integrate
def create3d():
grid_matrix = np.array([[1,1,1,1],[2,2,2,2],[3,3,3,3]])
fig = plt.figure()
ax = plt.axes(projection='3d')
p = ax.scatter3D(grid_matrix[:,0],grid_matrix[:,1] ,grid_matrix[:,2] , c=grid_matrix[:,3], cmap='viridis')
cb = fig.colorbar(p)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title(' Scatter Plot')
In order to use a 3d projection in matplotlib <= 3.1 you need to import axes3d, i.e.
from mpl_toolkits.mplot3d import Axes3D
From matplotlib >= 3.2, no extra import is necessary. So possibly you are running different matplotlib versions on both computers.
If you are running your code within an iPython kernel, Jupyter notebook for example,
then you only need to perform each import once and you will be able to run any code which relies on said import until the kernel is shutdown. However, in order to run the script in a self contained fashion you will need that import included in your script.