Matplotlib plot window is black
I recently started studying python and matplotlib. The problem I face is that I always get a black window as a plot output.
See simple code below.
import numpy as np import matplotlib.pyplot as plt import pylab x = np.arange(0, 5, 0.1) y = np.sin(x) #plot the x and y and you are supposed to see a sine curve plt.plot(x, y) pylab.show()
I get the same result executing code samples from matplotlib pages. Does anyone have any idea where this comes from and how to overcome this?
I'm using the Operating system Linx Mint.
See also questions close to this topic
psychopy - error when trying to set non-scalar variable via conditions file
In PsychoPy v1.85.1 I am configuring the 'polygon' stimuli object. I am trying to set the height attribute via a csv conditions file. I get an error message saying "Invalid parameter. Single numbers are not accepted"
PsychoPy v1.85.1 on Windows.
In the polygon's pop-up UI 'size' box I enter: $height
In the csv-file I have a 'height' column. Each row has values such as: (1.5, 0)
PsychoPy gives the error message:
File "C:\Program Files (x86)\PsychoPy2\lib\site-packages\psychopy \visual\basevisual.py", line 1312, in pos self.__dict__['pos'] = val2array(value, False, False) File "C:\Program Files (x86)\PsychoPy2\lib\site-packages\psychopy\tools\arraytools.py", line 176, in val2array raise ValueError(msg % str(length)) ValueError: Invalid parameter. Single numbers are not accepted. Should be tuple/list/array of length 2
Troubleshooting - Misc
- Scalar variables work in other csv columns work fine so PsychoPy connects with the csv-file.
- Tried xlsx format.
- Tried entering without parenthesis and with square bracket parenthesis
Troubleshooting - Running the code outside of PsychoPy
I go to the arraytools.py file and find the relevant code snippet. I paste it into a Python notebook (although it is python 3.3) and add some print rows for debugging:
# Copied code snippet from # C:\Program Files (x86)\PsychoPy2\lib\site-packages\psychopy\tools\arraytools.py import numpy def val2array(value, withNone=True, withScalar=True, length=2): """Helper function: converts different input to a numpy array. Raises informative error messages if input is invalid. withNone: True/False. should 'None' be passed? withScalar: True/False. is a scalar an accepted input? Will be converted to array of this scalar length: False / 2 / 3. Number of elements input should have or be converted to. Might be False (do not accept arrays or convert to such) """ if value is None: if withNone: return None else: raise ValueError('Invalid parameter. None is not accepted as ' 'value.') value = numpy.array(value, float) print ("value:", value) #I ADDED print ("value.shape:", value.shape) #I ADDED print ("numpy.product(value.shape):", numpy.product(value.shape)) #I ADDED if numpy.product(value.shape) == 1: #MY COMMENT: WHY DOES THIS EVALUTE TRUE? if withScalar: # e.g. 5 becomes array([5.0, 5.0, 5.0]) for length=3 return numpy.repeat(value, length) else: msg = ('Invalid parameter. Single numbers are not accepted. ' 'Should be tuple/list/array of length %s') raise ValueError(msg % str(length)) elif value.shape[-1] == length: return numpy.array(value, float) else: msg = 'Invalid parameter. Should be length %s but got length %s.' raise ValueError(msg % (str(length), str(len(value))))
I test it by entering a value and then run the function.
# Run the function value = (1.5,0.0) val2array(value, False, False, length =2)
Results below. Seems to work fine:
value: [ 1.5 0. ] value.shape: (2,) numpy.product(value.shape): 2 Out: array([ 1.5, 0. ])
Debugging in Coder View
Thank you Michael. It seems the input value becomes a unicode string which the numpy arrary function cannot convert
print "position: ", position print "type(position): ", type(position) print "numpy.array(position, float): ", np.array(position, float) #Results: position: (0, 0.5) type(position): <type 'unicode'> numpy.array(position, float): Traceback (most recent call last): File "C:\Users\nikla\Documents\PsychoPy\test2.py", line 127, in <module> print "numpy.array(position, float): ", np.array(position, float) ValueError: could not convert string to float: (0, 0.5)
Any idea what I am doing wrong?
pretty printing sympy array
I am trying to create 2-dim arrays in sympy but getting error. Here is my code:
from sympy import * from sympy.tensor.array import Array init_printing() x = symbols('x') vec1 = Array([ [x,x**2],[x**3,x**4] ]) print(vec1)
I am getting output as
[[x, x**2], [x**3, x**4]]
But I wanted to get output as pretty printed array like shown on http://docs.sympy.org/latest/tutorial/printing.html. How can I do that? I am using python 3.6 running on Spyder 3.4 on Windows.
Creating a column in a pandas dataframe containing the number elements in the group (groupby)
I'm analysis a large dataset containing a variable number of observations per subject (ranging from 1 occurrence to 26 occurrences...). As I would need to analyse the time between events, the subjects with only one occurrence are non-informative.
Previously, while working in Stata I would assign a variable (called eg. total) using Stata code:
by idnummer, sort: gen total=_N
In this way every line/subject has a variable 'total' and I could eliminate all subjects total=1.
I have been trying with agg functions and with size but I end up with 'NaN'...
PS: using the "similar questions" on the side I have found the answer to my own question....
df['total'] = df.groupby('idnummer')['sequence'].transform('max')
PyPlot ploting 3D rather than 2D
Could someone please help me with resolving the following: Using matplotlib and trying to plot dataFrame collected from oandapy
import numpy as np import pandas as pd import seaborn as sns; sns.set() import warnings warnings.simplefilter('ignore') path='c:\data' import oandapy as opy import matplotlib.pyplot as plt account_id = 'example id' token = 'example token' dates = pd.date_range(start='2017-01-01', end='2017-06-24', freq='B') %%time instrument = 'EUR_USD' df = pd.DataFrame() print 'Retrieving packeges for %s' % instrument for i in range(0, len(dates) - 1): d1 = str(dates).replace(' ', 'T') d2 = str(dates[i + 1]).replace(' ', 'T') try: data = oanda.get_history(instrument=instrument, start=d1, end=d2, granularity='D') df = df.append(pd.DataFrame(data['candles'])) except: pass if i % 25 == 0: print '%02d' % i df['closeAsk'].plot(figsize=(8,5));
How can I plot multiple splines when reading random data from txt files
import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import spline data = np.loadtxt('surging_data.txt', delimiter=',') x1=data[0:3,0] y1=data[0:3,1] x2=data[3:6,0] y2=data[3:6,1] x1_smooth = np.linspace(x1.min(),x1.max(),100) y1_smooth = spline(x1,y1, x1_smooth) x2_smooth = np.linspace(x2.min(),x2.max(),100) y2_smooth = spline(x2,y2, x2_smooth) plt.plot(x1_smooth,y1_smooth, marker= 'o',linestyle='solid', label='Exp 8-10') plt.plot(x2_smooth,y2_smooth, marker='*', linestyle='solid', label='Exp 12-14')
My data is in the following format:
0.0917,2.500,0.210207685 0.9999,1.250,0.129627709 8.5916,0.500,0.078210543 0.1023,2.250,0.195346414 1.0230,1.000,0.103702167 8.0873,0.500,0.060291812
I am not able to plot the splines for my data which I have read from txt files. When I simply plot it using array function or otherwise read from txt, it works good, but when I use the spline function, it gave the different/wrong plot. I think I am not able to define the correct function for x-smooth in my code. I have tried from available answers, but couldn't find one when extracting data from txt files. I am a very new user, so it would be great to have some help.
My actual plot is the one on left which is correct, but the one on the right is not correct after I try to draw the splines.
plt (matplotlib) not desplaying in a new window
I am trying to subplot two images aa and REFLECTANCE using
plt, the problem is that the figure is displayed in the console not in a new window, I need to have the figure in a new seperate window in order to save it and use it outside the code.
I beleive the problem is actually concerned with the version i'm using of Linux (Ubuntu) ? Or am I missing some line of code ?
Thank you for your help.
import matplotlib.pyplot as plt import numpy as np import cv2 directory = "/home/stagiaire/Bureau/tech/IMG_170622_081910_0004_RED.TIF" aa=cv2.imread(directory) plt.figure() plt.subplot(221), plt.imshow(aa),plt.title('Image originale') plt.subplot(222), plt.imshow(np.array(REFLECTANCE).reshape(1280,960).T),plt.title('Reflectance')